1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDBus module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qcoreapplication.h>
#include <qdebug.h>
#include <qmetaobject.h>
#include <qobject.h>
#include <qsocketnotifier.h>
#include <qstringlist.h>
#include <qtimer.h>
#include <qthread.h>
#include "qdbusargument.h"
#include "qdbusconnection_p.h"
#include "qdbusinterface_p.h"
#include "qdbusmessage.h"
#include "qdbusmetatype.h"
#include "qdbusmetatype_p.h"
#include "qdbusabstractadaptor.h"
#include "qdbusabstractadaptor_p.h"
#include "qdbusutil_p.h"
#include "qdbusmessage_p.h"
#include "qdbuscontext_p.h"
#include "qdbuspendingcall_p.h"
#include "qdbusintegrator_p.h"
#include "qdbusthreaddebug_p.h"
QT_BEGIN_NAMESPACE
static bool isDebugging;
#define qDBusDebug if (!::isDebugging); else qDebug
static inline QDebug operator<<(QDebug dbg, const QThread *th)
{
dbg.nospace() << "QThread(ptr=" << (void*)th;
if (th && !th->objectName().isEmpty())
dbg.nospace() << ", name=" << th->objectName();
dbg.nospace() << ')';
return dbg.space();
}
#if QDBUS_THREAD_DEBUG
static inline QDebug operator<<(QDebug dbg, const QDBusConnectionPrivate *conn)
{
dbg.nospace() << "QDBusConnection("
<< "ptr=" << (void*)conn
<< ", name=" << conn->name
<< ", baseService=" << conn->baseService
<< ", thread=";
if (conn->thread() == QThread::currentThread())
dbg.nospace() << "same thread";
else
dbg.nospace() << conn->thread();
dbg.nospace() << ')';
return dbg.space();
}
Q_AUTOTEST_EXPORT void qdbusDefaultThreadDebug(int action, int condition, QDBusConnectionPrivate *conn)
{
qDBusDebug() << QThread::currentThread()
<< "QtDBus threading action" << action
<< (condition == QDBusLockerBase::BeforeLock ? "before lock" :
condition == QDBusLockerBase::AfterLock ? "after lock" :
condition == QDBusLockerBase::BeforeUnlock ? "before unlock" :
condition == QDBusLockerBase::AfterUnlock ? "after unlock" :
condition == QDBusLockerBase::BeforePost ? "before event posting" :
condition == QDBusLockerBase::AfterPost ? "after event posting" :
condition == QDBusLockerBase::BeforeDeliver ? "before event delivery" :
condition == QDBusLockerBase::AfterDeliver ? "after event delivery" :
condition == QDBusLockerBase::BeforeAcquire ? "before acquire" :
condition == QDBusLockerBase::AfterAcquire ? "after acquire" :
condition == QDBusLockerBase::BeforeRelease ? "before release" :
condition == QDBusLockerBase::AfterRelease ? "after release" :
"condition unknown")
<< "in connection" << conn;
}
Q_AUTOTEST_EXPORT qdbusThreadDebugFunc qdbusThreadDebug = 0;
#endif
typedef void (*QDBusSpyHook)(const QDBusMessage&);
typedef QVarLengthArray<QDBusSpyHook, 4> QDBusSpyHookList;
Q_GLOBAL_STATIC(QDBusSpyHookList, qDBusSpyHookList)
extern "C" {
// libdbus-1 callbacks
static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms);
static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
{
Q_ASSERT(timeout);
Q_ASSERT(data);
// qDebug("addTimeout %d", q_dbus_timeout_get_interval(timeout));
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
if (!q_dbus_timeout_get_enabled(timeout))
return true;
QDBusWatchAndTimeoutLocker locker(AddTimeoutAction, d);
if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
// correct thread
return qDBusRealAddTimeout(d, timeout, q_dbus_timeout_get_interval(timeout));
} else {
// wrong thread: sync back
QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
ev->subtype = QDBusConnectionCallbackEvent::AddTimeout;
d->timeoutsPendingAdd.append(qMakePair(timeout, q_dbus_timeout_get_interval(timeout)));
d->postEventToThread(AddTimeoutAction, d, ev);
return true;
}
}
static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms)
{
Q_ASSERT(d->timeouts.keys(timeout).isEmpty());
int timerId = d->startTimer(ms);
if (!timerId)
return false;
d->timeouts[timerId] = timeout;
return true;
}
static void qDBusRemoveTimeout(DBusTimeout *timeout, void *data)
{
Q_ASSERT(timeout);
Q_ASSERT(data);
// qDebug("removeTimeout");
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
QDBusWatchAndTimeoutLocker locker(RemoveTimeoutAction, d);
// is it pending addition?
QDBusConnectionPrivate::PendingTimeoutList::iterator pit = d->timeoutsPendingAdd.begin();
while (pit != d->timeoutsPendingAdd.end()) {
if (pit->first == timeout)
pit = d->timeoutsPendingAdd.erase(pit);
else
++pit;
}
// is it a running timer?
bool correctThread = QCoreApplication::instance() && QThread::currentThread() == d->thread();
QDBusConnectionPrivate::TimeoutHash::iterator it = d->timeouts.begin();
while (it != d->timeouts.end()) {
if (it.value() == timeout) {
if (correctThread) {
// correct thread
d->killTimer(it.key());
} else {
// incorrect thread or no application, post an event for later
QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
ev->subtype = QDBusConnectionCallbackEvent::KillTimer;
ev->timerId = it.key();
d->postEventToThread(KillTimerAction, d, ev);
}
it = d->timeouts.erase(it);
break;
} else {
++it;
}
}
}
static void qDBusToggleTimeout(DBusTimeout *timeout, void *data)
{
Q_ASSERT(timeout);
Q_ASSERT(data);
//qDebug("ToggleTimeout");
qDBusRemoveTimeout(timeout, data);
qDBusAddTimeout(timeout, data);
}
static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd);
static dbus_bool_t qDBusAddWatch(DBusWatch *watch, void *data)
{
Q_ASSERT(watch);
Q_ASSERT(data);
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
int flags = q_dbus_watch_get_flags(watch);
int fd = q_dbus_watch_get_fd(watch);
if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
return qDBusRealAddWatch(d, watch, flags, fd);
} else {
QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
ev->subtype = QDBusConnectionCallbackEvent::AddWatch;
ev->watch = watch;
ev->fd = fd;
ev->extra = flags;
d->postEventToThread(AddWatchAction, d, ev);
return true;
}
}
static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd)
{
QDBusConnectionPrivate::Watcher watcher;
QDBusWatchAndTimeoutLocker locker(AddWatchAction, d);
if (flags & DBUS_WATCH_READABLE) {
//qDebug("addReadWatch %d", fd);
watcher.watch = watch;
if (QCoreApplication::instance()) {
watcher.read = new QSocketNotifier(fd, QSocketNotifier::Read, d);
watcher.read->setEnabled(q_dbus_watch_get_enabled(watch));
d->connect(watcher.read, SIGNAL(activated(int)), SLOT(socketRead(int)));
}
}
if (flags & DBUS_WATCH_WRITABLE) {
//qDebug("addWriteWatch %d", fd);
watcher.watch = watch;
if (QCoreApplication::instance()) {
watcher.write = new QSocketNotifier(fd, QSocketNotifier::Write, d);
watcher.write->setEnabled(q_dbus_watch_get_enabled(watch));
d->connect(watcher.write, SIGNAL(activated(int)), SLOT(socketWrite(int)));
}
}
d->watchers.insertMulti(fd, watcher);
return true;
}
static void qDBusRemoveWatch(DBusWatch *watch, void *data)
{
Q_ASSERT(watch);
Q_ASSERT(data);
//qDebug("remove watch");
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
int fd = q_dbus_watch_get_fd(watch);
QDBusWatchAndTimeoutLocker locker(RemoveWatchAction, d);
QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
while (i != d->watchers.end() && i.key() == fd) {
if (i.value().watch == watch) {
if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
// correct thread, delete the socket notifiers
delete i.value().read;
delete i.value().write;
} else {
// incorrect thread or no application, use delete later
if (i->read)
i->read->deleteLater();
if (i->write)
i->write->deleteLater();
}
i = d->watchers.erase(i);
} else {
++i;
}
}
}
static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd);
static void qDBusToggleWatch(DBusWatch *watch, void *data)
{
Q_ASSERT(watch);
Q_ASSERT(data);
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
int fd = q_dbus_watch_get_fd(watch);
if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
qDBusRealToggleWatch(d, watch, fd);
} else {
QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
ev->subtype = QDBusConnectionCallbackEvent::ToggleWatch;
ev->watch = watch;
ev->fd = fd;
d->postEventToThread(ToggleWatchAction, d, ev);
}
}
static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd)
{
QDBusWatchAndTimeoutLocker locker(ToggleWatchAction, d);
QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
while (i != d->watchers.end() && i.key() == fd) {
if (i.value().watch == watch) {
bool enabled = q_dbus_watch_get_enabled(watch);
int flags = q_dbus_watch_get_flags(watch);
//qDebug("toggle watch %d to %d (write: %d, read: %d)", q_dbus_watch_get_fd(watch), enabled, flags & DBUS_WATCH_WRITABLE, flags & DBUS_WATCH_READABLE);
if (flags & DBUS_WATCH_READABLE && i.value().read)
i.value().read->setEnabled(enabled);
if (flags & DBUS_WATCH_WRITABLE && i.value().write)
i.value().write->setEnabled(enabled);
return;
}
++i;
}
}
static void qDBusUpdateDispatchStatus(DBusConnection *connection, DBusDispatchStatus new_status, void *data)
{
Q_ASSERT(connection);
Q_UNUSED(connection);
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
static int slotId; // 0 is QObject::deleteLater()
if (!slotId) {
// it's ok to do this: there's no race condition because the store is atomic
// and we always set to the same value
slotId = QDBusConnectionPrivate::staticMetaObject.indexOfSlot("doDispatch()");
}
//qDBusDebug() << "Updating dispatcher status" << slotId;
if (new_status == DBUS_DISPATCH_DATA_REMAINS)
QDBusConnectionPrivate::staticMetaObject.method(slotId).
invoke(d, Qt::QueuedConnection);
}
static void qDBusNewConnection(DBusServer *server, DBusConnection *connection, void *data)
{
// ### We may want to separate the server from the QDBusConnectionPrivate
Q_ASSERT(server); Q_UNUSED(server);
Q_ASSERT(connection);
Q_ASSERT(data);
// keep the connection alive
q_dbus_connection_ref(connection);
QDBusConnectionPrivate *d = new QDBusConnectionPrivate;
// setConnection does the error handling for us
QDBusErrorInternal error;
d->setPeer(connection, error);
QDBusConnection retval = QDBusConnectionPrivate::q(d);
d->setBusService(retval);
//d->name = QString::number(reinterpret_cast<int>(d));
//d->setConnection(d->name, d);
// make QDBusServer emit the newConnection signal
QDBusConnectionPrivate *server_d = static_cast<QDBusConnectionPrivate *>(data);
server_d->serverConnection(retval);
}
} // extern "C"
static QByteArray buildMatchRule(const QString &service,
const QString &objectPath, const QString &interface,
const QString &member, const QStringList &argMatch, const QString & /*signature*/)
{
QString result = QLatin1String("type='signal',");
QString keyValue = QLatin1String("%1='%2',");
if (!service.isEmpty())
result += keyValue.arg(QLatin1String("sender"), service);
if (!objectPath.isEmpty())
result += keyValue.arg(QLatin1String("path"), objectPath);
if (!interface.isEmpty())
result += keyValue.arg(QLatin1String("interface"), interface);
if (!member.isEmpty())
result += keyValue.arg(QLatin1String("member"), member);
// add the argument string-matching now
if (!argMatch.isEmpty()) {
keyValue = QLatin1String("arg%1='%2',");
for (int i = 0; i < argMatch.count(); ++i)
if (!argMatch.at(i).isNull())
result += keyValue.arg(i).arg(argMatch.at(i));
}
result.chop(1); // remove ending comma
return result.toLatin1();
}
static bool findObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
const QString &fullpath, int &usedLength,
QDBusConnectionPrivate::ObjectTreeNode &result)
{
int start = 0;
int length = fullpath.length();
if (fullpath.at(0) == QLatin1Char('/'))
start = 1;
// walk the object tree
const QDBusConnectionPrivate::ObjectTreeNode *node = root;
while (start < length && node && !(node->flags & QDBusConnection::ExportChildObjects)) {
int end = fullpath.indexOf(QLatin1Char('/'), start);
end = (end == -1 ? length : end);
QStringRef pathComponent(&fullpath, start, end - start);
QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
qLowerBound(node->children.constBegin(), node->children.constEnd(), pathComponent);
if (it != node->children.constEnd() && it->name == pathComponent)
// match
node = it;
else
node = 0;
start = end + 1;
}
// found our object
usedLength = (start > length ? length : start);
if (node) {
if (node->obj || !node->children.isEmpty())
result = *node;
else
// there really is no object here
// we're just looking at an unused space in the QVector
node = 0;
}
return node;
}
static QObject *findChildObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
const QString &fullpath, int start)
{
int length = fullpath.length();
// any object in the tree can tell us to switch to its own object tree:
const QDBusConnectionPrivate::ObjectTreeNode *node = root;
if (node && node->flags & QDBusConnection::ExportChildObjects) {
QObject *obj = node->obj;
while (obj) {
if (start >= length)
// we're at the correct level
return obj;
int pos = fullpath.indexOf(QLatin1Char('/'), start);
pos = (pos == -1 ? length : pos);
QStringRef pathComponent(&fullpath, start, pos - start);
const QObjectList children = obj->children();
// find a child with the proper name
QObject *next = 0;
QObjectList::ConstIterator it = children.constBegin();
QObjectList::ConstIterator end = children.constEnd();
for ( ; it != end; ++it)
if ((*it)->objectName() == pathComponent) {
next = *it;
break;
}
if (!next)
break;
obj = next;
start = pos + 1;
}
}
// object not found
return 0;
}
static bool shouldWatchService(const QString &service)
{
return !service.isEmpty() && !service.startsWith(QLatin1Char(':'));
}
extern QDBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook);
void qDBusAddSpyHook(QDBusSpyHook hook)
{
qDBusSpyHookList()->append(hook);
}
extern "C" {
static DBusHandlerResult
qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
{
Q_ASSERT(data);
Q_UNUSED(connection);
QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
if (d->mode == QDBusConnectionPrivate::InvalidMode)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(message);
qDBusDebug() << d << "got message (signal):" << amsg;
return d->handleMessage(amsg) ?
DBUS_HANDLER_RESULT_HANDLED :
DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
}
bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
{
const QDBusSpyHookList *list = qDBusSpyHookList();
for (int i = 0; i < list->size(); ++i) {
qDBusDebug() << "calling the message spy hook";
(*(*list)[i])(amsg);
}
switch (amsg.type()) {
case QDBusMessage::SignalMessage:
handleSignal(amsg);
return true;
break;
case QDBusMessage::MethodCallMessage:
handleObjectCall(amsg);
return true;
case QDBusMessage::ReplyMessage:
case QDBusMessage::ErrorMessage:
return false; // we don't handle those here
case QDBusMessage::InvalidMessage:
Q_ASSERT_X(false, "QDBusConnection", "Invalid message found when processing");
break;
}
return false;
}
static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode &haystack)
{
QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it = haystack.children.begin();
QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator end = haystack.children.end();
for ( ; it != end; ++it)
huntAndDestroy(needle, *it);
if (needle == haystack.obj) {
haystack.obj = 0;
haystack.flags = 0;
}
}
static void huntAndEmit(DBusConnection *connection, DBusMessage *msg,
QObject *needle, const QDBusConnectionPrivate::ObjectTreeNode &haystack,
bool isScriptable, bool isAdaptor, const QString &path = QString())
{
QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it = haystack.children.constBegin();
QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end = haystack.children.constEnd();
for ( ; it != end; ++it)
huntAndEmit(connection, msg, needle, *it, isScriptable, isAdaptor, path + QLatin1Char('/') + it->name);
if (needle == haystack.obj) {
// is this a signal we should relay?
if (isAdaptor && (haystack.flags & QDBusConnection::ExportAdaptors) == 0)
return; // no: it comes from an adaptor and we're not exporting adaptors
else if (!isAdaptor) {
int mask = isScriptable
? QDBusConnection::ExportScriptableSignals
: QDBusConnection::ExportNonScriptableSignals;
if ((haystack.flags & mask) == 0)
return; // signal was not exported
}
QByteArray p = path.toLatin1();
if (p.isEmpty())
p = "/";
qDBusDebug() << QThread::currentThread() << "emitting signal at" << p;
DBusMessage *msg2 = q_dbus_message_copy(msg);
q_dbus_message_set_path(msg2, p);
q_dbus_connection_send(connection, msg2, 0);
q_dbus_message_unref(msg2);
}
}
static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
const QString &signature_, QList<int>& metaTypes)
{
QByteArray msgSignature = signature_.toLatin1();
for (int idx = mo->methodCount() - 1 ; idx >= QObject::staticMetaObject.methodCount(); --idx) {
QMetaMethod mm = mo->method(idx);
// check access:
if (mm.access() != QMetaMethod::Public)
continue;
// check type:
if (mm.methodType() != QMetaMethod::Slot)
continue;
// check name:
QByteArray slotname = mm.signature();
int paren = slotname.indexOf('(');
if (paren != name.length() || !slotname.startsWith(name))
continue;
int returnType = qDBusNameToTypeId(mm.typeName());
bool isAsync = qDBusCheckAsyncTag(mm.tag());
bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
// consistency check:
if (isAsync && returnType != QMetaType::Void)
continue;
int inputCount = qDBusParametersForMethod(mm, metaTypes);
if (inputCount == -1)
continue; // problem parsing
metaTypes[0] = returnType;
bool hasMessage = false;
if (inputCount > 0 &&
metaTypes.at(inputCount) == QDBusMetaTypeId::message) {
// "no input parameters" is allowed as long as the message meta type is there
hasMessage = true;
--inputCount;
}
// try to match the parameters
int i;
QByteArray reconstructedSignature;
for (i = 1; i <= inputCount; ++i) {
const char *typeSignature = QDBusMetaType::typeToSignature( metaTypes.at(i) );
if (!typeSignature)
break; // invalid
reconstructedSignature += typeSignature;
if (!msgSignature.startsWith(reconstructedSignature))
break;
}
if (reconstructedSignature != msgSignature)
continue; // we didn't match them all
if (hasMessage)
++i;
// make sure that the output parameters have signatures too
if (returnType != 0 && QDBusMetaType::typeToSignature(returnType) == 0)
continue;
bool ok = true;
for (int j = i; ok && j < metaTypes.count(); ++j)
if (QDBusMetaType::typeToSignature(metaTypes.at(i)) == 0)
ok = false;
if (!ok)
continue;
// consistency check:
if (isAsync && metaTypes.count() > i + 1)
continue;
if (isScriptable && (flags & QDBusConnection::ExportScriptableSlots) == 0)
continue; // not exported
if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableSlots) == 0)
continue; // not exported
// if we got here, this slot matched
return idx;
}
// no slot matched
return -1;
}
QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
QObject *object, int idx,
const QList<int> &metaTypes,
const QDBusMessage &msg)
{
Q_ASSERT(object);
Q_UNUSED(object);
int n = metaTypes.count() - 1;
if (metaTypes[n] == QDBusMetaTypeId::message)
--n;
// check that types match
for (int i = 0; i < n; ++i)
if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() &&
msg.arguments().at(i).userType() != qMetaTypeId<QDBusArgument>())
return 0; // no match
// we can deliver
// prepare for the call
return new QDBusCallDeliveryEvent(QDBusConnection(target), idx, target, msg, metaTypes);
}
void QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
const QDBusMessage &msg)
{
// This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
// that was received from D-Bus
//
// Signals are delivered to slots if the parameters match
// Slots can have less parameters than there are on the message
// Slots can optionally have one final parameter that is a QDBusMessage
// Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
QDBusCallDeliveryEvent *call = prepareReply(this, hook.obj, hook.midx, hook.params, msg);
if (call)
postEventToThread(ActivateSignalAction, hook.obj, call);
}
bool QDBusConnectionPrivate::activateCall(QObject* object, int flags, const QDBusMessage &msg)
{
// This is called by QDBusConnectionPrivate::handleObjectCall to place a call
// to a slot on the object.
//
// The call is delivered to the first slot that matches the following conditions:
// - has the same name as the message's target member
// - ALL of the message's types are found in slot's parameter list
// - optionally has one more parameter of type QDBusMessage
// If none match, then the slot of the same name as the message target and with
// the first type of QDBusMessage is delivered.
//
// The D-Bus specification requires that all MethodCall messages be replied to, unless the
// caller specifically waived this requirement. This means that we inspect if the user slot
// generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
// QDBusMessage parameter, it cannot generate a reply.
//
// When a return message is generated, the slot's return type, if any, will be placed
// in the message's first position. If there are non-const reference parameters to the
// slot, they must appear at the end and will be placed in the subsequent message
// positions.
static const char cachePropertyName[] = "_qdbus_slotCache";
if (!object)
return false;
Q_ASSERT_X(QThread::currentThread() == object->thread(),
"QDBusConnection: internal threading error",
"function called for an object that is in another thread!!");
QDBusSlotCache slotCache =
qvariant_cast<QDBusSlotCache>(object->property(cachePropertyName));
QString cacheKey = msg.member(), signature = msg.signature();
if (!signature.isEmpty()) {
cacheKey.reserve(cacheKey.length() + 1 + signature.length());
cacheKey += QLatin1Char('.');
cacheKey += signature;
}
QDBusSlotCache::Hash::ConstIterator cacheIt = slotCache.hash.constFind(cacheKey);
while (cacheIt != slotCache.hash.constEnd() && cacheIt->flags != flags &&
cacheIt.key() == cacheKey)
++cacheIt;
if (cacheIt == slotCache.hash.constEnd() || cacheIt.key() != cacheKey)
{
// not cached, analyse the meta object
const QMetaObject *mo = object->metaObject();
QByteArray memberName = msg.member().toUtf8();
// find a slot that matches according to the rules above
QDBusSlotCache::Data slotData;
slotData.flags = flags;
slotData.slotIdx = ::findSlot(mo, memberName, flags, msg.signature(), slotData.metaTypes);
if (slotData.slotIdx == -1) {
// ### this is where we want to add the connection as an arg too
// try with no parameters, but with a QDBusMessage
slotData.slotIdx = ::findSlot(mo, memberName, flags, QString(), slotData.metaTypes);
if (slotData.metaTypes.count() != 2 ||
slotData.metaTypes.at(1) != QDBusMetaTypeId::message) {
// not found
// save the negative lookup
slotData.slotIdx = -1;
slotData.metaTypes.clear();
slotCache.hash.insert(cacheKey, slotData);
object->setProperty(cachePropertyName, qVariantFromValue(slotCache));
return false;
}
}
// save to the cache
slotCache.hash.insert(cacheKey, slotData);
object->setProperty(cachePropertyName, qVariantFromValue(slotCache));
// found the slot to be called
deliverCall(object, flags, msg, slotData.metaTypes, slotData.slotIdx);
return true;
} else if (cacheIt->slotIdx == -1) {
// negative cache
return false;
} else {
// use the cache
deliverCall(object, flags, msg, cacheIt->metaTypes, cacheIt->slotIdx);
return true;
}
}
void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const QDBusMessage &msg,
const QList<int> &metaTypes, int slotIdx)
{
Q_ASSERT_X(!object || QThread::currentThread() == object->thread(),
"QDBusConnection: internal threading error",
"function called for an object that is in another thread!!");
QVarLengthArray<void *, 10> params;
params.reserve(metaTypes.count());
QVariantList auxParameters;
// let's create the parameter list
// first one is the return type -- add it below
params.append(0);
// add the input parameters
int i;
int pCount = qMin(msg.arguments().count(), metaTypes.count() - 1);
for (i = 1; i <= pCount; ++i) {
int id = metaTypes[i];
if (id == QDBusMetaTypeId::message)
break;
const QVariant &arg = msg.arguments().at(i - 1);
if (arg.userType() == id)
// no conversion needed
params.append(const_cast<void *>(arg.constData()));
else if (arg.userType() == qMetaTypeId<QDBusArgument>()) {
// convert to what the function expects
void *null = 0;
auxParameters.append(QVariant(id, null));
const QDBusArgument &in =
*reinterpret_cast<const QDBusArgument *>(arg.constData());
QVariant &out = auxParameters[auxParameters.count() - 1];
if (!QDBusMetaType::demarshall(in, out.userType(), out.data()))
qFatal("Internal error: demarshalling function for type '%s' (%d) failed!",
out.typeName(), out.userType());
params.append(const_cast<void *>(out.constData()));
} else {
qFatal("Internal error: got invalid meta type %d (%s) "
"when trying to convert to meta type %d (%s)",
arg.userType(), QMetaType::typeName(arg.userType()),
id, QMetaType::typeName(id));
}
}
bool takesMessage = false;
if (metaTypes.count() > i && metaTypes[i] == QDBusMetaTypeId::message) {
params.append(const_cast<void*>(static_cast<const void*>(&msg)));
takesMessage = true;
++i;
}
// output arguments
QVariantList outputArgs;
void *null = 0;
if (metaTypes[0] != QMetaType::Void) {
QVariant arg(metaTypes[0], null);
outputArgs.append( arg );
params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
}
for ( ; i < metaTypes.count(); ++i) {
QVariant arg(metaTypes[i], null);
outputArgs.append( arg );
params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
}
// make call:
bool fail;
if (!object) {
fail = true;
} else {
// FIXME: save the old sender!
QDBusContextPrivate context(QDBusConnection(this), msg);
QDBusContextPrivate *old = QDBusContextPrivate::set(object, &context);
QDBusConnectionPrivate::setSender(this);
QPointer<QObject> ptr = object;
fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
slotIdx, params.data()) >= 0;
QDBusConnectionPrivate::setSender(0);
// the object might be deleted in the slot
if (!ptr.isNull())
QDBusContextPrivate::set(object, old);
}
// do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
// yet.
if (msg.isReplyRequired() && !msg.isDelayedReply()) {
if (!fail) {
// normal reply
qDBusDebug() << this << "Automatically sending reply:" << outputArgs;
send(msg.createReply(outputArgs));
} else {
// generate internal error
qWarning("Internal error: Failed to deliver message");
send(msg.createErrorReply(QDBusError::InternalError,
QLatin1String("Failed to deliver message")));
}
}
return;
}
extern bool qDBusInitThreads();
QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
: QObject(p), ref(1), mode(InvalidMode), connection(0), server(0), busService(0),
watchAndTimeoutLock(QMutex::Recursive),
rootNode(QString(QLatin1Char('/')))
{
static const bool threads = q_dbus_threads_init_default();
static const int debugging = qgetenv("QDBUS_DEBUG").toInt();
::isDebugging = debugging;
Q_UNUSED(threads)
Q_UNUSED(debugging)
#ifdef QDBUS_THREAD_DEBUG
if (debugging > 1)
qdbusThreadDebug = qdbusDefaultThreadDebug;
#endif
QDBusMetaTypeId::init();
rootNode.flags = 0;
}
QDBusConnectionPrivate::~QDBusConnectionPrivate()
{
if (thread() && thread() != QThread::currentThread())
qWarning("QDBusConnection(name=\"%s\")'s last reference in not in its creation thread! "
"Timer and socket errors will follow and the program will probably crash",
qPrintable(name));
closeConnection();
rootNode.children.clear(); // free resources
qDeleteAll(cachedMetaObjects);
if (server)
q_dbus_server_unref(server);
if (connection)
q_dbus_connection_unref(connection);
connection = 0;
server = 0;
}
void QDBusConnectionPrivate::deleteYourself()
{
if (thread() && thread() != QThread::currentThread()) {
// last reference dropped while not in the correct thread
// ask the correct thread to delete
// note: since we're posting an event to another thread, we
// must consider deleteLater() to take effect immediately
deleteLater();
} else {
delete this;
}
}
void QDBusConnectionPrivate::closeConnection()
{
QDBusWriteLocker locker(CloseConnectionAction, this);
ConnectionMode oldMode = mode;
mode = InvalidMode; // prevent reentrancy
baseService.clear();
if (oldMode == ServerMode) {
if (server) {
q_dbus_server_disconnect(server);
}
} else if (oldMode == ClientMode || oldMode == PeerMode) {
if (connection) {
q_dbus_connection_close(connection);
// send the "close" message
while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS)
;
}
}
}
void QDBusConnectionPrivate::checkThread()
{
if (!thread()) {
if (QCoreApplication::instance())
moveToThread(QCoreApplication::instance()->thread());
else
qWarning("The thread that had QDBusConnection('%s') has died and there is no main thread",
qPrintable(name));
}
}
bool QDBusConnectionPrivate::handleError(const QDBusErrorInternal &error)
{
if (!error)
return false; // no error
//lock.lockForWrite();
lastError = error;
//lock.unlock();
return true;
}
void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
{
{
QDBusWatchAndTimeoutLocker locker(TimerEventAction, this);
DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
if (timeout)
q_dbus_timeout_handle(timeout);
}
doDispatch();
}
void QDBusConnectionPrivate::customEvent(QEvent *e)
{
Q_ASSERT(e->type() == QEvent::User);
QDBusConnectionCallbackEvent *ev = static_cast<QDBusConnectionCallbackEvent *>(e);
QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
QDBusLockerBase::BeforeDeliver, this);
switch (ev->subtype)
{
case QDBusConnectionCallbackEvent::AddTimeout: {
QDBusWatchAndTimeoutLocker locker(RealAddTimeoutAction, this);
while (!timeoutsPendingAdd.isEmpty()) {
QPair<DBusTimeout *, int> entry = timeoutsPendingAdd.takeFirst();
qDBusRealAddTimeout(this, entry.first, entry.second);
}
break;
}
case QDBusConnectionCallbackEvent::KillTimer:
killTimer(ev->timerId);
break;
case QDBusConnectionCallbackEvent::AddWatch:
qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
break;
case QDBusConnectionCallbackEvent::ToggleWatch:
qDBusRealToggleWatch(this, ev->watch, ev->fd);
break;
}
QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
QDBusLockerBase::AfterDeliver, this);
}
void QDBusConnectionPrivate::doDispatch()
{
QDBusDispatchLocker locker(DoDispatchAction, this);
if (mode == ClientMode || mode == PeerMode)
while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
}
void QDBusConnectionPrivate::socketRead(int fd)
{
QVarLengthArray<DBusWatch *, 2> pendingWatches;
{
QDBusWatchAndTimeoutLocker locker(SocketReadAction, this);
WatcherHash::ConstIterator it = watchers.constFind(fd);
while (it != watchers.constEnd() && it.key() == fd) {
if (it->watch && it->read && it->read->isEnabled())
pendingWatches.append(it.value().watch);
++it;
}
}
for (int i = 0; i < pendingWatches.size(); ++i)
if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_READABLE))
qDebug("OUT OF MEM");
doDispatch();
}
void QDBusConnectionPrivate::socketWrite(int fd)
{
QVarLengthArray<DBusWatch *, 2> pendingWatches;
{
QDBusWatchAndTimeoutLocker locker(SocketWriteAction, this);
WatcherHash::ConstIterator it = watchers.constFind(fd);
while (it != watchers.constEnd() && it.key() == fd) {
if (it->watch && it->write && it->write->isEnabled())
pendingWatches.append(it.value().watch);
++it;
}
}
for (int i = 0; i < pendingWatches.size(); ++i)
if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_WRITABLE))
qDebug("OUT OF MEM");
}
void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
{
QDBusWriteLocker locker(ObjectDestroyedAction, this);
huntAndDestroy(obj, rootNode);
SignalHookHash::iterator sit = signalHooks.begin();
while (sit != signalHooks.end()) {
if (static_cast<QObject *>(sit.value().obj) == obj)
sit = disconnectSignal(sit);
else
++sit;
}
obj->disconnect(this);
}
void QDBusConnectionPrivate::relaySignal(QObject *obj, const QMetaObject *mo, int signalId,
const QVariantList &args)
{
QString interface = qDBusInterfaceFromMetaObject(mo);
QMetaMethod mm = mo->method(signalId);
QByteArray memberName = mm.signature();
memberName.truncate(memberName.indexOf('('));
// check if it's scriptable
bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
bool isAdaptor = false;
for ( ; mo; mo = mo->superClass())
if (mo == &QDBusAbstractAdaptor::staticMetaObject) {
isAdaptor = true;
break;
}
QDBusReadLocker locker(RelaySignalAction, this);
QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/"), interface,
QLatin1String(memberName));
QDBusMessagePrivate::setParametersValidated(message, true);
message.setArguments(args);
QDBusError error;
DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &error);
if (!msg) {
qWarning("QDBusConnection: Could not emit signal %s.%s: %s", qPrintable(interface), memberName.constData(),
qPrintable(error.message()));
lastError = error;
return;
}
//qDBusDebug() << "Emitting signal" << message;
//qDBusDebug() << "for paths:";
q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
huntAndEmit(connection, msg, obj, rootNode, isScriptable, isAdaptor);
q_dbus_message_unref(msg);
}
void QDBusConnectionPrivate::_q_serviceOwnerChanged(const QString &name,
const QString &oldOwner, const QString &newOwner)
{
Q_UNUSED(oldOwner);
QDBusWriteLocker locker(UpdateSignalHookOwnerAction, this);
WatchedServicesHash::Iterator it = watchedServices.find(name);
if (it == watchedServices.end())
return;
if (oldOwner != it->owner)
qWarning("QDBusConnection: name '%s' had owner '%s' but we thought it was '%s'",
qPrintable(name), qPrintable(oldOwner), qPrintable(it->owner));
qDBusDebug() << this << "Updating name" << name << "from" << oldOwner << "to" << newOwner;
it->owner = newOwner;
}
int QDBusConnectionPrivate::findSlot(QObject* obj, const QByteArray &normalizedName,
QList<int> ¶ms)
{
int midx = obj->metaObject()->indexOfMethod(normalizedName);
if (midx == -1)
return -1;
int inputCount = qDBusParametersForMethod(obj->metaObject()->method(midx), params);
if ( inputCount == -1 || inputCount + 1 != params.count() )
return -1; // failed to parse or invalid arguments or output arguments
return midx;
}
bool QDBusConnectionPrivate::prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
const QString &service,
const QString &path, const QString &interface, const QString &name,
const QStringList &argMatch,
QObject *receiver, const char *signal, int minMIdx,
bool buildSignature)
{
QByteArray normalizedName = signal + 1;
hook.midx = findSlot(receiver, signal + 1, hook.params);
if (hook.midx == -1) {
normalizedName = QMetaObject::normalizedSignature(signal + 1);
hook.midx = findSlot(receiver, normalizedName, hook.params);
}
if (hook.midx < minMIdx) {
if (hook.midx == -1)
{}
return false;
}
hook.service = service;
hook.path = path;
hook.obj = receiver;
hook.argumentMatch = argMatch;
// build the D-Bus signal name and signature
// This should not happen for QDBusConnection::connect, use buildSignature here, since
// QDBusConnection::connect passes false and everything else uses true
QString mname = name;
if (buildSignature && mname.isNull()) {
normalizedName.truncate(normalizedName.indexOf('('));
mname = QString::fromUtf8(normalizedName);
}
key = mname;
key.reserve(interface.length() + 1 + mname.length());
key += QLatin1Char(':');
key += interface;
if (buildSignature) {
hook.signature.clear();
for (int i = 1; i < hook.params.count(); ++i)
if (hook.params.at(i) != QDBusMetaTypeId::message)
hook.signature += QLatin1String( QDBusMetaType::typeToSignature( hook.params.at(i) ) );
}
hook.matchRule = buildMatchRule(service, path, interface, mname, argMatch, hook.signature);
return true; // connect to this signal
}
void QDBusConnectionPrivate::sendError(const QDBusMessage &msg, QDBusError::ErrorType code)
{
if (code == QDBusError::UnknownMethod) {
QString interfaceMsg;
if (msg.interface().isEmpty())
interfaceMsg = QLatin1String("any interface");
else
interfaceMsg = QString::fromLatin1("interface '%1'").arg(msg.interface());
send(msg.createErrorReply(code,
QString::fromLatin1("No such method '%1' in %2 at object path '%3' "
"(signature '%4')")
.arg(msg.member(), interfaceMsg, msg.path(), msg.signature())));
} else if (code == QDBusError::UnknownInterface) {
send(msg.createErrorReply(QDBusError::UnknownInterface,
QString::fromLatin1("No such interface '%1' at object path '%2'")
.arg(msg.interface(), msg.path())));
} else if (code == QDBusError::UnknownObject) {
send(msg.createErrorReply(QDBusError::UnknownObject,
QString::fromLatin1("No such object path '%1'").arg(msg.path())));
}
}
bool QDBusConnectionPrivate::activateInternalFilters(const ObjectTreeNode &node,
const QDBusMessage &msg)
{
// object may be null
const QString interface = msg.interface();
if (interface.isEmpty() || interface == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE)) {
if (msg.member() == QLatin1String("Introspect") && msg.signature().isEmpty()) {
//qDebug() << "QDBusConnectionPrivate::activateInternalFilters introspect" << msg.d_ptr->msg;
QDBusMessage reply = msg.createReply(qDBusIntrospectObject(node));
send(reply);
return true;
}
if (!interface.isEmpty()) {
sendError(msg, QDBusError::UnknownMethod);
return true;
}
}
if (node.obj && (interface.isEmpty() ||
interface == QLatin1String(DBUS_INTERFACE_PROPERTIES))) {
//qDebug() << "QDBusConnectionPrivate::activateInternalFilters properties" << msg.d_ptr->msg;
if (msg.member() == QLatin1String("Get") && msg.signature() == QLatin1String("ss")) {
QDBusMessage reply = qDBusPropertyGet(node, msg);
send(reply);
return true;
} else if (msg.member() == QLatin1String("Set") && msg.signature() == QLatin1String("ssv")) {
QDBusMessage reply = qDBusPropertySet(node, msg);
send(reply);
return true;
} else if (msg.member() == QLatin1String("GetAll") && msg.signature() == QLatin1String("s")) {
QDBusMessage reply = qDBusPropertyGetAll(node, msg);
send(reply);
return true;
}
if (!interface.isEmpty()) {
sendError(msg, QDBusError::UnknownMethod);
return true;
}
}
return false;
}
void QDBusConnectionPrivate::activateObject(ObjectTreeNode &node, const QDBusMessage &msg,
int pathStartPos)
{
// This is called by QDBusConnectionPrivate::handleObjectCall to place a call to a slot
// on the object.
//
// The call is routed through the adaptor sub-objects if we have any
// object may be null
if (pathStartPos != msg.path().length()) {
node.flags &= ~QDBusConnection::ExportAllSignals;
node.obj = findChildObject(&node, msg.path(), pathStartPos);
if (!node.obj) {
sendError(msg, QDBusError::UnknownObject);
return;
}
}
QDBusAdaptorConnector *connector;
if (node.flags & QDBusConnection::ExportAdaptors &&
(connector = qDBusFindAdaptorConnector(node.obj))) {
int newflags = node.flags | QDBusConnection::ExportAllSlots;
if (msg.interface().isEmpty()) {
// place the call in all interfaces
// let the first one that handles it to work
QDBusAdaptorConnector::AdaptorMap::ConstIterator it =
connector->adaptors.constBegin();
QDBusAdaptorConnector::AdaptorMap::ConstIterator end =
connector->adaptors.constEnd();
for ( ; it != end; ++it)
if (activateCall(it->adaptor, newflags, msg))
return;
} else {
// check if we have an interface matching the name that was asked:
QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
msg.interface());
if (it != connector->adaptors.constEnd() && msg.interface() == QLatin1String(it->interface)) {
if (!activateCall(it->adaptor, newflags, msg))
sendError(msg, QDBusError::UnknownMethod);
return;
}
}
}
// no adaptors matched or were exported
// try our standard filters
if (activateInternalFilters(node, msg))
return; // internal filters have already run or an error has been sent
// try the object itself:
if (node.flags & (QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportNonScriptableSlots)) {
bool interfaceFound = true;
if (!msg.interface().isEmpty())
interfaceFound = qDBusInterfaceInObject(node.obj, msg.interface());
if (interfaceFound) {
if (!activateCall(node.obj, node.flags, msg))
sendError(msg, QDBusError::UnknownMethod);
return;
}
}
// nothing matched, send an error code
if (msg.interface().isEmpty())
sendError(msg, QDBusError::UnknownMethod);
else
sendError(msg, QDBusError::UnknownInterface);
}
void QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
{
// if the msg is external, we were called from inside doDispatch
// that means the dispatchLock mutex is locked
// must not call out to user code in that case
//
// however, if the message is internal, handleMessage was called
// directly and no lock is in place. We can therefore call out to
// user code, if necessary
ObjectTreeNode result;
int usedLength;
QThread *objThread = 0;
QSemaphore sem;
bool semWait;
{
QDBusReadLocker locker(HandleObjectCallAction, this);
if (!findObject(&rootNode, msg.path(), usedLength, result)) {
// qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
sendError(msg, QDBusError::UnknownObject);
return;
}
if (!result.obj) {
// no object -> no threading issues
// it's either going to be an error, or an internal filter
activateObject(result, msg, usedLength);
return;
}
objThread = result.obj->thread();
if (!objThread) {
send(msg.createErrorReply(QDBusError::InternalError,
QString::fromLatin1("Object '%1' (at path '%2')"
" has no thread. Cannot deliver message.")
.arg(result.obj->objectName(), msg.path())));
return;
}
if (!QDBusMessagePrivate::isLocal(msg)) {
// external incoming message
// post it and forget
postEventToThread(HandleObjectCallPostEventAction, result.obj,
new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
usedLength, msg));
return;
} else if (objThread != QThread::currentThread()) {
// synchronize with other thread
postEventToThread(HandleObjectCallPostEventAction, result.obj,
new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
usedLength, msg, &sem));
semWait = true;
} else {
semWait = false;
}
} // release the lock
if (semWait)
SEM_ACQUIRE(HandleObjectCallSemaphoreAction, sem);
else
activateObject(result, msg, usedLength);
}
QDBusActivateObjectEvent::~QDBusActivateObjectEvent()
{
if (!handled) {
// we're being destroyed without delivering
// it means the object was deleted between posting and delivering
QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
that->sendError(message, QDBusError::UnknownObject);
}
// semaphore releasing happens in ~QMetaCallEvent
}
int QDBusActivateObjectEvent::placeMetaCall(QObject *)
{
QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
QDBusLockerBase::BeforeDeliver, that);
that->activateObject(node, message, pathStartPos);
QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
QDBusLockerBase::AfterDeliver, that);
handled = true;
return -1;
}
void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
{
SignalHookHash::const_iterator it = signalHooks.find(key);
SignalHookHash::const_iterator end = signalHooks.constEnd();
//qDebug("looking for: %s", path.toLocal8Bit().constData());
//qDBusDebug() << signalHooks.keys();
for ( ; it != end && it.key() == key; ++it) {
const SignalHook &hook = it.value();
if (!hook.service.isEmpty()) {
const QString owner =
shouldWatchService(hook.service) ?
watchedServices.value(hook.service).owner :
hook.service;
if (owner != msg.service())
continue;
}
if (!hook.path.isEmpty() && hook.path != msg.path())
continue;
if (!hook.signature.isEmpty() && hook.signature != msg.signature())
continue;
if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
continue;
if (!hook.argumentMatch.isEmpty()) {
const QVariantList arguments = msg.arguments();
if (hook.argumentMatch.size() > arguments.size())
continue;
bool matched = true;
for (int i = 0; i < hook.argumentMatch.size(); ++i) {
const QString ¶m = hook.argumentMatch.at(i);
if (param.isNull())
continue; // don't try to match against this
if (param == arguments.at(i).toString())
continue; // matched
matched = false;
break;
}
if (!matched)
continue;
}
activateSignal(hook, msg);
}
}
void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
{
// We call handlesignal(QString, QDBusMessage) three times:
// one with member:interface
// one with member:
// one with :interface
// This allows us to match signals with wildcards on member or interface
// (but not both)
QString key = msg.member();
key.reserve(key.length() + 1 + msg.interface().length());
key += QLatin1Char(':');
key += msg.interface();
QDBusReadLocker locker(HandleSignalAction, this);
handleSignal(key, msg); // one try
key.truncate(msg.member().length() + 1); // keep the ':'
handleSignal(key, msg); // second try
key = QLatin1Char(':');
key += msg.interface();
handleSignal(key, msg); // third try
}
static dbus_int32_t server_slot = -1;
void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
{
if (!s) {
handleError(error);
return;
}
server = s;
mode = ServerMode;
dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
if (data_allocated && server_slot < 0)
return;
dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
qDBusAddWatch,
qDBusRemoveWatch,
qDBusToggleWatch,
this, 0);
//qDebug() << "watch_functions_set" << watch_functions_set;
Q_UNUSED(watch_functions_set);
dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
qDBusAddTimeout,
qDBusRemoveTimeout,
qDBusToggleTimeout,
this, 0);
//qDebug() << "time_functions_set" << time_functions_set;
Q_UNUSED(time_functions_set);
q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
//qDebug() << "data_set" << data_set;
Q_UNUSED(data_set);
}
void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
{
if (!c) {
handleError(error);
return;
}
connection = c;
mode = PeerMode;
q_dbus_connection_set_exit_on_disconnect(connection, false);
q_dbus_connection_set_watch_functions(connection,
qDBusAddWatch,
qDBusRemoveWatch,
qDBusToggleWatch,
this, 0);
q_dbus_connection_set_timeout_functions(connection,
qDBusAddTimeout,
qDBusRemoveTimeout,
qDBusToggleTimeout,
this, 0);
q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
q_dbus_connection_add_filter(connection,
qDBusSignalFilter,
this, 0);
QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
}
void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
{
if (!dbc) {
handleError(error);
return;
}
connection = dbc;
mode = ClientMode;
q_dbus_connection_set_exit_on_disconnect(connection, false);
q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
qDBusToggleWatch, this, 0);
q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
qDBusToggleTimeout, this, 0);
q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
// Initialize the match rules
// We want all messages that have us as destination
// signals don't have destinations, but connectSignal() takes care of them
const char *service = q_dbus_bus_get_unique_name(connection);
if (service) {
QVarLengthArray<char, 56> filter;
filter.append("destination='", 13);
filter.append(service, qstrlen(service));
filter.append("\'\0", 2);
QDBusErrorInternal error;
q_dbus_bus_add_match(connection, filter.constData(), error);
if (handleError(error)) {
closeConnection();
return;
}
baseService = QString::fromUtf8(service);
} else {
qWarning("QDBusConnectionPrivate::setConnection: Unable to get base service");
}
QString busService = QLatin1String(DBUS_SERVICE_DBUS);
connectSignal(busService, QString(), QString(), QLatin1String("NameAcquired"), QStringList(), QString(),
this, SLOT(registerService(QString)));
connectSignal(busService, QString(), QString(), QLatin1String("NameLost"), QStringList(), QString(),
this, SLOT(unregisterService(QString)));
q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
qDBusDebug() << this << ": connected successfully";
// schedule a dispatch:
QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
}
extern "C"{
static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
{
QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
Q_ASSERT(call->pending == pending);
Q_UNUSED(pending);
QDBusConnectionPrivate::processFinishedCall(call);
}
}
void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
{
Q_ASSERT(pcall->pending);
Q_ASSERT(!pcall->autoDelete);
//Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
if (pcall->waitingForFinished) {
// another thread is already waiting
pcall->waitForFinishedCondition.wait(&pcall->mutex);
} else {
pcall->waitingForFinished = true;
pcall->mutex.unlock();
{
QDBusDispatchLocker locker(PendingCallBlockAction, this);
q_dbus_pending_call_block(pcall->pending);
// QDBusConnectionPrivate::processFinishedCall() is called automatically
}
pcall->mutex.lock();
}
}
void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
{
QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
QMutexLocker locker(&call->mutex);
QDBusMessage &msg = call->replyMessage;
if (call->pending) {
// decode the message
DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
msg = QDBusMessagePrivate::fromDBusMessage(reply);
q_dbus_message_unref(reply);
}
qDBusDebug() << connection << "got message reply (async):" << msg;
// Check if the reply has the expected signature
call->checkReceivedSignature();
if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
// Deliver the return values of a remote function call.
//
// There is only one connection and it is specified by idx
// The slot must have the same parameter types that the message does
// The slot may have less parameters than the message
// The slot may optionally have one final parameter that is QDBusMessage
// The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
call->metaTypes, msg);
if (e)
connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
else
qDBusDebug() << "Deliver failed!";
}
if (call->pending)
q_dbus_pending_call_unref(call->pending);
call->pending = 0;
locker.unlock();
// Are there any watchers?
if (call->watcherHelper)
call->watcherHelper->emitSignals(msg, call->sentMessage);
if (msg.type() == QDBusMessage::ErrorMessage)
emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
if (call->autoDelete) {
Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
delete call;
}
}
int QDBusConnectionPrivate::send(const QDBusMessage& message)
{
if (QDBusMessagePrivate::isLocal(message))
return -1; // don't send; the reply will be retrieved by the caller
// through the d_ptr->localReply link
QDBusError error;
DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &error);
if (!msg) {
if (message.type() == QDBusMessage::MethodCallMessage)
qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
qPrintable(message.service()), qPrintable(message.path()),
qPrintable(message.interface()), qPrintable(message.member()),
qPrintable(error.message()));
else if (message.type() == QDBusMessage::SignalMessage)
qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
qPrintable(message.path()), qPrintable(message.interface()),
qPrintable(message.member()),
qPrintable(error.message()));
else
qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
message.type() == QDBusMessage::ReplyMessage ? "reply" :
message.type() == QDBusMessage::ErrorMessage ? "error" :
"invalid", qPrintable(message.service()),
qPrintable(error.message()));
lastError = error;
return 0;
}
q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
qDBusDebug() << this << "sending message (no reply):" << message;
checkThread();
bool isOk = q_dbus_connection_send(connection, msg, 0);
int serial = 0;
if (isOk)
serial = q_dbus_message_get_serial(msg);
q_dbus_message_unref(msg);
return serial;
}
QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
int sendMode, int timeout)
{
checkThread();
if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
&& isServiceRegisteredByThread(message.service()))
// special case for synchronous local calls
return sendWithReplyLocal(message);
if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
QDBusError err;
DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &err);
if (!msg) {
qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
qPrintable(message.service()), qPrintable(message.path()),
qPrintable(message.interface()), qPrintable(message.member()),
qPrintable(err.message()));
lastError = err;
return QDBusMessage::createError(err);
}
qDBusDebug() << this << "sending message (blocking):" << message;
QDBusErrorInternal error;
DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
q_dbus_message_unref(msg);
if (!!error) {
lastError = err = error;
return QDBusMessage::createError(err);
}
QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply);
q_dbus_message_unref(reply);
qDBusDebug() << this << "got message reply (blocking):" << amsg;
return amsg;
} else { // use the event loop
QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
Q_ASSERT(pcall);
if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
QEventLoop loop;
loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
// enter the event loop and wait for a reply
loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
}
QDBusMessage reply = pcall->replyMessage;
lastError = reply; // set or clear error
delete pcall;
return reply;
}
}
QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
{
qDBusDebug() << this << "sending message via local-loop:" << message;
QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
bool handled = handleMessage(localCallMsg);
if (!handled) {
QString interface = message.interface();
if (interface.isEmpty())
interface = QLatin1String("<no-interface>");
return QDBusMessage::createError(QDBusError::InternalError,
QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
.arg(interface, message.member(),
message.path(), message.signature()));
}
// if the message was handled, there might be a reply
QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
"on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
qPrintable(message.signature()));
return QDBusMessage::createError(
QDBusError(QDBusError::InternalError,
QLatin1String("local-loop message cannot have delayed replies")));
}
// there is a reply
qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
return localReplyMsg;
}
QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
int timeout)
{
if (isServiceRegisteredByThread(message.service())) {
// special case for local calls
QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
pcall->replyMessage = sendWithReplyLocal(message);
return pcall;
}
checkThread();
QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
pcall->ref = 0;
QDBusError error;
DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &error);
if (!msg) {
qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
qPrintable(message.service()), qPrintable(message.path()),
qPrintable(message.interface()), qPrintable(message.member()),
qPrintable(error.message()));
pcall->replyMessage = QDBusMessage::createError(error);
lastError = error;
return pcall;
}
qDBusDebug() << this << "sending message (async):" << message;
DBusPendingCall *pending = 0;
QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
if (pending) {
q_dbus_message_unref(msg);
pcall->pending = pending;
q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
return pcall;
} else {
// we're probably disconnected at this point
lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
}
} else {
lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
}
q_dbus_message_unref(msg);
pcall->replyMessage = QDBusMessage::createError(error);
return pcall;
}
int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
const char *returnMethod, const char *errorMethod,
int timeout)
{
QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
Q_ASSERT(pcall);
// has it already finished with success (dispatched locally)?
if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
pcall->setReplyCallback(receiver, returnMethod);
processFinishedCall(pcall);
delete pcall;
return 1;
}
// either it hasn't finished or it has finished with error
if (errorMethod) {
pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
Qt::QueuedConnection);
pcall->watcherHelper->moveToThread(thread());
}
// has it already finished and is an error reply message?
if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
processFinishedCall(pcall);
delete pcall;
return 1;
}
pcall->autoDelete = true;
pcall->ref.ref();
pcall->setReplyCallback(receiver, returnMethod);
return 1;
}
bool QDBusConnectionPrivate::connectSignal(const QString &service,
const QString &path, const QString &interface, const QString &name,
const QStringList &argumentMatch, const QString &signature,
QObject *receiver, const char *slot)
{
// check the slot
QDBusConnectionPrivate::SignalHook hook;
QString key;
QString name2 = name;
if (name2.isNull())
name2.detach();
hook.signature = signature;
if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
return false; // don't connect
// avoid duplicating:
QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.find(key);
QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
for ( ; it != end && it.key() == key; ++it) {
const QDBusConnectionPrivate::SignalHook &entry = it.value();
if (entry.service == hook.service &&
entry.path == hook.path &&
entry.signature == hook.signature &&
entry.obj == hook.obj &&
entry.midx == hook.midx &&
entry.argumentMatch == hook.argumentMatch) {
// no need to compare the parameters if it's the same slot
return true; // already there
}
}
connectSignal(key, hook);
return true;
}
void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
{
signalHooks.insertMulti(key, hook);
connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
if (it != matchRefCounts.end()) { // Match already present
it.value() = it.value() + 1;
return;
}
matchRefCounts.insert(hook.matchRule, 1);
if (connection) {
qDBusDebug("Adding rule: %s", hook.matchRule.constData());
QDBusErrorInternal error;
q_dbus_bus_add_match(connection, hook.matchRule, error);
if (!!error) {
QDBusError qerror = error;
qWarning("QDBusConnectionPrivate::connectSignal: received error from D-Bus server "
"while connecting signal to %s::%s: %s (%s)",
hook.obj->metaObject()->className(),
hook.obj->metaObject()->method(hook.midx).signature(),
qPrintable(qerror.name()), qPrintable(qerror.message()));
Q_ASSERT(false);
} else {
// Successfully connected the signal
// Do we need to watch for this name?
if (shouldWatchService(hook.service)) {
WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
if (++data.refcount == 1) {
// we need to watch for this service changing
QString dbusServerService = QLatin1String(DBUS_SERVICE_DBUS);
connectSignal(dbusServerService, QString(), QLatin1String(DBUS_INTERFACE_DBUS),
QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
data.owner = getNameOwnerNoCache(hook.service);
qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
<< data.owner << ")";
}
}
}
}
}
bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
const QString &path, const QString &interface, const QString &name,
const QStringList &argumentMatch, const QString &signature,
QObject *receiver, const char *slot)
{
// check the slot
QDBusConnectionPrivate::SignalHook hook;
QString key;
QString name2 = name;
if (name2.isNull())
name2.detach();
hook.signature = signature;
if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
return false; // don't disconnect
// avoid duplicating:
QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
for ( ; it != end && it.key() == key; ++it) {
const QDBusConnectionPrivate::SignalHook &entry = it.value();
if (entry.service == hook.service &&
entry.path == hook.path &&
entry.signature == hook.signature &&
entry.obj == hook.obj &&
entry.midx == hook.midx &&
entry.argumentMatch == hook.argumentMatch) {
// no need to compare the parameters if it's the same slot
disconnectSignal(it);
return true; // it was there
}
}
// the slot was not found
return false;
}
QDBusConnectionPrivate::SignalHookHash::Iterator
QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
{
const SignalHook &hook = it.value();
bool erase = false;
MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
if (i == matchRefCounts.end()) {
qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
} else {
if (i.value() == 1) {
erase = true;
matchRefCounts.erase(i);
}
else {
i.value() = i.value() - 1;
}
}
// we don't care about errors here
if (connection && erase) {
qDBusDebug("Removing rule: %s", hook.matchRule.constData());
q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
// Successfully disconnected the signal
// Were we watching for this name?
WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
if (sit != watchedServices.end()) {
if (--sit.value().refcount == 0) {
watchedServices.erase(sit);
QString dbusServerService = QLatin1String(DBUS_SERVICE_DBUS);
disconnectSignal(dbusServerService, QString(), QLatin1String(DBUS_INTERFACE_DBUS),
QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
}
}
}
return signalHooks.erase(it);
}
void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
{
connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
Qt::DirectConnection);
if (node->flags & (QDBusConnection::ExportAdaptors
| QDBusConnection::ExportScriptableSignals
| QDBusConnection::ExportNonScriptableSignals)) {
QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
if (node->flags & (QDBusConnection::ExportScriptableSignals
| QDBusConnection::ExportNonScriptableSignals)) {
connector->disconnectAllSignals(node->obj);
connector->connectAllSignals(node->obj);
}
// disconnect and reconnect to avoid duplicates
connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
Qt::DirectConnection);
}
}
void QDBusConnectionPrivate::connectRelay(const QString &service,
const QString &path, const QString &interface,
QDBusAbstractInterface *receiver,
const char *signal)
{
// this function is called by QDBusAbstractInterface when one of its signals is connected
// we set up a relay from D-Bus into it
SignalHook hook;
QString key;
if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
QDBusAbstractInterface::staticMetaObject.methodCount(), true))
return; // don't connect
// add it to our list:
QDBusWriteLocker locker(ConnectRelayAction, this);
SignalHookHash::ConstIterator it = signalHooks.find(key);
SignalHookHash::ConstIterator end = signalHooks.constEnd();
for ( ; it != end && it.key() == key; ++it) {
const SignalHook &entry = it.value();
if (entry.service == hook.service &&
entry.path == hook.path &&
entry.signature == hook.signature &&
entry.obj == hook.obj &&
entry.midx == hook.midx)
return; // already there, no need to re-add
}
connectSignal(key, hook);
}
void QDBusConnectionPrivate::disconnectRelay(const QString &service,
const QString &path, const QString &interface,
QDBusAbstractInterface *receiver,
const char *signal)
{
// this function is called by QDBusAbstractInterface when one of its signals is disconnected
// we remove relay from D-Bus into it
SignalHook hook;
QString key;
if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
QDBusAbstractInterface::staticMetaObject.methodCount(), true))
return; // don't connect
// remove it from our list:
QDBusWriteLocker locker(DisconnectRelayAction, this);
SignalHookHash::Iterator it = signalHooks.find(key);
SignalHookHash::Iterator end = signalHooks.end();
for ( ; it != end && it.key() == key; ++it) {
const SignalHook &entry = it.value();
if (entry.service == hook.service &&
entry.path == hook.path &&
entry.signature == hook.signature &&
entry.obj == hook.obj &&
entry.midx == hook.midx) {
// found it
disconnectSignal(it);
return;
}
}
qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
}
QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
{
if (QDBusUtil::isValidUniqueConnectionName(serviceName))
return serviceName;
if (!connection)
return QString();
{
// acquire a read lock for the cache
QReadLocker locker(&lock);
WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
if (it != watchedServices.constEnd())
return it->owner;
}
// not cached
return getNameOwnerNoCache(serviceName);
}
QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
{
QDBusMessage msg = QDBusMessage::createMethodCall(QLatin1String(DBUS_SERVICE_DBUS),
QLatin1String(DBUS_PATH_DBUS), QLatin1String(DBUS_INTERFACE_DBUS),
QLatin1String("GetNameOwner"));
QDBusMessagePrivate::setParametersValidated(msg, true);
msg << serviceName;
QDBusMessage reply = sendWithReply(msg, QDBus::Block);
if (reply.type() == QDBusMessage::ReplyMessage)
return reply.arguments().at(0).toString();
return QString();
}
QDBusMetaObject *
QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
const QString &interface, QDBusError &error)
{
// service must be a unique connection name
if (!interface.isEmpty()) {
QDBusReadLocker locker(FindMetaObject1Action, this);
QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
if (mo)
return mo;
}
// introspect the target object
QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
QLatin1String("Introspect"));
QDBusMessagePrivate::setParametersValidated(msg, true);
QDBusMessage reply = sendWithReply(msg, QDBus::Block);
// it doesn't exist yet, we have to create it
QDBusWriteLocker locker(FindMetaObject2Action, this);
QDBusMetaObject *mo = 0;
if (!interface.isEmpty())
mo = cachedMetaObjects.value(interface, 0);
if (mo)
// maybe it got created when we switched from read to write lock
return mo;
QString xml;
if (reply.type() == QDBusMessage::ReplyMessage) {
if (reply.signature() == QLatin1String("s"))
// fetch the XML description
xml = reply.arguments().at(0).toString();
} else {
error = reply;
lastError = error;
if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
return 0; // error
}
// release the lock and return
QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
cachedMetaObjects, error);
lastError = error;
return result;
}
void QDBusConnectionPrivate::registerService(const QString &serviceName)
{
QDBusWriteLocker locker(RegisterServiceAction, this);
serviceNames.append(serviceName);
}
void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
{
QDBusWriteLocker locker(UnregisterServiceAction, this);
serviceNames.removeAll(serviceName);
}
bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
{
if (serviceName == baseService)
return true;
QStringList copy = serviceNames;
return copy.contains(serviceName);
}
void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
{
QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
QCoreApplication::postEvent(object, ev);
QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
}
QT_END_NAMESPACE
|