1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Copyright (C) 2016 Intel Corporation.
5 ** Contact: https://www.qt.io/licensing/
6 **
7 ** This file is part of the QtDBus module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial License Usage
11 ** Licensees holding valid commercial Qt licenses may use this file in
12 ** accordance with the commercial license agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and The Qt Company. For licensing terms
15 ** and conditions see https://www.qt.io/terms-conditions. For further
16 ** information use the contact form at https://www.qt.io/contact-us.
17 **
18 ** GNU Lesser General Public License Usage
19 ** Alternatively, this file may be used under the terms of the GNU Lesser
20 ** General Public License version 3 as published by the Free Software
21 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
22 ** packaging of this file. Please review the following information to
23 ** ensure the GNU Lesser General Public License version 3 requirements
24 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25 **
26 ** GNU General Public License Usage
27 ** Alternatively, this file may be used under the terms of the GNU
28 ** General Public License version 2.0 or (at your option) the GNU General
29 ** Public license version 3 or any later version approved by the KDE Free
30 ** Qt Foundation. The licenses are as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32 ** included in the packaging of this file. Please review the following
33 ** information to ensure the GNU General Public License requirements will
34 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35 ** https://www.gnu.org/licenses/gpl-3.0.html.
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41 #include "qdbusconnection_p.h"
42
43 #include "qdbus_symbols_p.h"
44 #include <QtCore/qcoreapplication.h>
45 #include <QtCore/qmetaobject.h>
46 #include <QtCore/qstringlist.h>
47 #include <QtCore/qthread.h>
48
49 #include "qdbusabstractadaptor.h"
50 #include "qdbusabstractadaptor_p.h"
51 #include "qdbusconnection.h"
52 #include "qdbusextratypes.h"
53 #include "qdbusmessage.h"
54 #include "qdbusmetatype.h"
55 #include "qdbusmetatype_p.h"
56 #include "qdbusmessage_p.h"
57 #include "qdbusutil_p.h"
58 #include "qdbusvirtualobject.h"
59
60 #include <algorithm>
61
62 #ifndef QT_NO_DBUS
63
64 QT_BEGIN_NAMESPACE
65
66 // defined in qdbusxmlgenerator.cpp
67 extern QString qDBusGenerateMetaObjectXml(QString interface, const QMetaObject *mo,
68 const QMetaObject *base, int flags);
69
70 static const char introspectableInterfaceXml[] =
71 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
72 " <method name=\"Introspect\">\n"
73 " <arg name=\"xml_data\" type=\"s\" direction=\"out\"/>\n"
74 " </method>\n"
75 " </interface>\n";
76
77 static const char propertiesInterfaceXml[] =
78 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
79 " <method name=\"Get\">\n"
80 " <arg name=\"interface_name\" type=\"s\" direction=\"in\"/>\n"
81 " <arg name=\"property_name\" type=\"s\" direction=\"in\"/>\n"
82 " <arg name=\"value\" type=\"v\" direction=\"out\"/>\n"
83 " </method>\n"
84 " <method name=\"Set\">\n"
85 " <arg name=\"interface_name\" type=\"s\" direction=\"in\"/>\n"
86 " <arg name=\"property_name\" type=\"s\" direction=\"in\"/>\n"
87 " <arg name=\"value\" type=\"v\" direction=\"in\"/>\n"
88 " </method>\n"
89 " <method name=\"GetAll\">\n"
90 " <arg name=\"interface_name\" type=\"s\" direction=\"in\"/>\n"
91 " <arg name=\"values\" type=\"a{sv}\" direction=\"out\"/>\n"
92 " <annotation name=\"org.qtproject.QtDBus.QtTypeName.Out0\" value=\"QVariantMap\"/>\n"
93 " </method>\n"
94 " <signal name=\"PropertiesChanged\">\n"
95 " <arg name=\"interface_name\" type=\"s\" direction=\"out\"/>\n"
96 " <arg name=\"changed_properties\" type=\"a{sv}\" direction=\"out\"/>\n"
97 " <annotation name=\"org.qtproject.QtDBus.QtTypeName.Out1\" value=\"QVariantMap\"/>\n"
98 " <arg name=\"invalidated_properties\" type=\"as\" direction=\"out\"/>\n"
99 " </signal>\n"
100 " </interface>\n";
101
102 static const char peerInterfaceXml[] =
103 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
104 " <method name=\"Ping\"/>\n"
105 " <method name=\"GetMachineId\">\n"
106 " <arg name=\"machine_uuid\" type=\"s\" direction=\"out\"/>\n"
107 " </method>\n"
108 " </interface>\n";
109
generateSubObjectXml(QObject * object)110 static QString generateSubObjectXml(QObject *object)
111 {
112 QString retval;
113 const QObjectList &objs = object->children();
114 QObjectList::ConstIterator it = objs.constBegin();
115 QObjectList::ConstIterator end = objs.constEnd();
116 for ( ; it != end; ++it) {
117 QString name = (*it)->objectName();
118 if (!name.isEmpty() && QDBusUtil::isValidPartOfObjectPath(name))
119 retval += QLatin1String(" <node name=\"") + name + QLatin1String("\"/>\n");
120 }
121 return retval;
122 }
123
124 // declared as extern in qdbusconnection_p.h
125
qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode & node,const QString & path)126 QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node, const QString &path)
127 {
128 // object may be null
129
130 QString xml_data(QLatin1String(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE));
131 xml_data += QLatin1String("<node>\n");
132
133 if (node.obj) {
134 Q_ASSERT_X(QThread::currentThread() == node.obj->thread(),
135 "QDBusConnection: internal threading error",
136 "function called for an object that is in another thread!!");
137
138 if (node.flags & (QDBusConnection::ExportScriptableContents
139 | QDBusConnection::ExportNonScriptableContents)) {
140 // create XML for the object itself
141 const QMetaObject *mo = node.obj->metaObject();
142 for ( ; mo != &QObject::staticMetaObject; mo = mo->superClass())
143 xml_data += qDBusGenerateMetaObjectXml(node.interfaceName, mo, mo->superClass(),
144 node.flags);
145 }
146
147 // does this object have adaptors?
148 QDBusAdaptorConnector *connector;
149 if (node.flags & QDBusConnection::ExportAdaptors &&
150 (connector = qDBusFindAdaptorConnector(node.obj))) {
151
152 // trasverse every adaptor in this object
153 QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin();
154 QDBusAdaptorConnector::AdaptorMap::ConstIterator end = connector->adaptors.constEnd();
155 for ( ; it != end; ++it) {
156 // add the interface:
157 QString ifaceXml = QDBusAbstractAdaptorPrivate::retrieveIntrospectionXml(it->adaptor);
158 if (ifaceXml.isEmpty()) {
159 // add the interface's contents:
160 ifaceXml += qDBusGenerateMetaObjectXml(QString::fromLatin1(it->interface),
161 it->adaptor->metaObject(),
162 &QDBusAbstractAdaptor::staticMetaObject,
163 QDBusConnection::ExportScriptableContents
164 | QDBusConnection::ExportNonScriptableContents);
165
166 QDBusAbstractAdaptorPrivate::saveIntrospectionXml(it->adaptor, ifaceXml);
167 }
168
169 xml_data += ifaceXml;
170 }
171 }
172
173 // is it a virtual node that handles introspection itself?
174 if (node.flags & QDBusConnectionPrivate::VirtualObject) {
175 xml_data += node.treeNode->introspect(path);
176 }
177
178 xml_data += QLatin1String( propertiesInterfaceXml );
179 }
180
181 xml_data += QLatin1String( introspectableInterfaceXml );
182 xml_data += QLatin1String( peerInterfaceXml );
183
184 if (node.flags & QDBusConnection::ExportChildObjects) {
185 xml_data += generateSubObjectXml(node.obj);
186 } else {
187 // generate from the object tree
188 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
189 node.children.constBegin();
190 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end =
191 node.children.constEnd();
192 for ( ; it != end; ++it)
193 if (it->obj || !it->children.isEmpty())
194 xml_data += QLatin1String(" <node name=\"") + it->name + QLatin1String("\"/>\n");
195 }
196
197 xml_data += QLatin1String("</node>\n");
198 return xml_data;
199 }
200
201 // implement the D-Bus interface org.freedesktop.DBus.Properties
202
interfaceNotFoundError(const QDBusMessage & msg,const QString & interface_name)203 static inline QDBusMessage interfaceNotFoundError(const QDBusMessage &msg, const QString &interface_name)
204 {
205 return msg.createErrorReply(QDBusError::UnknownInterface,
206 QLatin1String("Interface %1 was not found in object %2")
207 .arg(interface_name, msg.path()));
208 }
209
210 static inline QDBusMessage
propertyNotFoundError(const QDBusMessage & msg,const QString & interface_name,const QByteArray & property_name)211 propertyNotFoundError(const QDBusMessage &msg, const QString &interface_name, const QByteArray &property_name)
212 {
213 return msg.createErrorReply(QDBusError::UnknownProperty,
214 QLatin1String("Property %1%2%3 was not found in object %4")
215 .arg(interface_name,
216 QLatin1String(interface_name.isEmpty() ? "" : "."),
217 QLatin1String(property_name),
218 msg.path()));
219 }
220
qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode & node,const QDBusMessage & msg)221 QDBusMessage qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode &node,
222 const QDBusMessage &msg)
223 {
224 Q_ASSERT(msg.arguments().count() == 2);
225 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
226 "QDBusConnection: internal threading error",
227 "function called for an object that is in another thread!!");
228
229 QString interface_name = msg.arguments().at(0).toString();
230 QByteArray property_name = msg.arguments().at(1).toString().toUtf8();
231
232 QDBusAdaptorConnector *connector;
233 QVariant value;
234 bool interfaceFound = false;
235 if (node.flags & QDBusConnection::ExportAdaptors &&
236 (connector = qDBusFindAdaptorConnector(node.obj))) {
237
238 // find the class that implements interface_name or try until we've found the property
239 // in case of an empty interface
240 if (interface_name.isEmpty()) {
241 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
242 end = connector->adaptors.constEnd(); it != end; ++it) {
243 const QMetaObject *mo = it->adaptor->metaObject();
244 int pidx = mo->indexOfProperty(property_name);
245 if (pidx != -1) {
246 value = mo->property(pidx).read(it->adaptor);
247 break;
248 }
249 }
250 } else {
251 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
252 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
253 interface_name);
254 if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
255 interfaceFound = true;
256 value = it->adaptor->property(property_name);
257 }
258 }
259 }
260
261 if (!interfaceFound && !value.isValid()
262 && node.flags & (QDBusConnection::ExportAllProperties |
263 QDBusConnection::ExportNonScriptableProperties)) {
264 // try the object itself
265 if (!interface_name.isEmpty())
266 interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);
267
268 if (interfaceFound) {
269 int pidx = node.obj->metaObject()->indexOfProperty(property_name);
270 if (pidx != -1) {
271 QMetaProperty mp = node.obj->metaObject()->property(pidx);
272 if ((mp.isScriptable() && (node.flags & QDBusConnection::ExportScriptableProperties)) ||
273 (!mp.isScriptable() && (node.flags & QDBusConnection::ExportNonScriptableProperties)))
274 value = mp.read(node.obj);
275 }
276 }
277 }
278
279 if (!value.isValid()) {
280 // the property was not found
281 if (!interfaceFound)
282 return interfaceNotFoundError(msg, interface_name);
283 return propertyNotFoundError(msg, interface_name, property_name);
284 }
285
286 return msg.createReply(QVariant::fromValue(QDBusVariant(value)));
287 }
288
289 enum PropertyWriteResult {
290 PropertyWriteSuccess = 0,
291 PropertyNotFound,
292 PropertyTypeMismatch,
293 PropertyReadOnly,
294 PropertyWriteFailed
295 };
296
propertyWriteReply(const QDBusMessage & msg,const QString & interface_name,const QByteArray & property_name,int status)297 static QDBusMessage propertyWriteReply(const QDBusMessage &msg, const QString &interface_name,
298 const QByteArray &property_name, int status)
299 {
300 switch (status) {
301 case PropertyNotFound:
302 return propertyNotFoundError(msg, interface_name, property_name);
303 case PropertyTypeMismatch:
304 return msg.createErrorReply(QDBusError::InvalidArgs,
305 QLatin1String("Invalid arguments for writing to property %1%2%3")
306 .arg(interface_name,
307 QLatin1String(interface_name.isEmpty() ? "" : "."),
308 QLatin1String(property_name)));
309 case PropertyReadOnly:
310 return msg.createErrorReply(QDBusError::PropertyReadOnly,
311 QLatin1String("Property %1%2%3 is read-only")
312 .arg(interface_name,
313 QLatin1String(interface_name.isEmpty() ? "" : "."),
314 QLatin1String(property_name)));
315 case PropertyWriteFailed:
316 return msg.createErrorReply(QDBusError::InternalError,
317 QString::fromLatin1("Internal error"));
318
319 case PropertyWriteSuccess:
320 return msg.createReply();
321 }
322 Q_ASSERT_X(false, "", "Should not be reached");
323 return QDBusMessage();
324 }
325
writeProperty(QObject * obj,const QByteArray & property_name,QVariant value,int propFlags=QDBusConnection::ExportAllProperties)326 static int writeProperty(QObject *obj, const QByteArray &property_name, QVariant value,
327 int propFlags = QDBusConnection::ExportAllProperties)
328 {
329 const QMetaObject *mo = obj->metaObject();
330 int pidx = mo->indexOfProperty(property_name);
331 if (pidx == -1) {
332 // this object has no property by that name
333 return PropertyNotFound;
334 }
335
336 QMetaProperty mp = mo->property(pidx);
337
338 // check if this property is writable
339 if (!mp.isWritable())
340 return PropertyReadOnly;
341
342 // check if this property is exported
343 bool isScriptable = mp.isScriptable();
344 if (!(propFlags & QDBusConnection::ExportScriptableProperties) && isScriptable)
345 return PropertyNotFound;
346 if (!(propFlags & QDBusConnection::ExportNonScriptableProperties) && !isScriptable)
347 return PropertyNotFound;
348
349 // we found our property
350 // do we have the right type?
351 int id = mp.userType();
352 if (!id){
353 // type not registered or invalid / void?
354 qWarning("QDBusConnection: Unable to handle unregistered datatype '%s' for property '%s::%s'",
355 mp.typeName(), mo->className(), property_name.constData());
356 return PropertyWriteFailed;
357 }
358
359 if (id != QMetaType::QVariant && value.userType() == QDBusMetaTypeId::argument()) {
360 // we have to demarshall before writing
361 void *null = nullptr;
362 QVariant other(id, null);
363 if (!QDBusMetaType::demarshall(qvariant_cast<QDBusArgument>(value), id, other.data())) {
364 qWarning("QDBusConnection: type `%s' (%d) is not registered with QtDBus. "
365 "Use qDBusRegisterMetaType to register it",
366 mp.typeName(), id);
367 return PropertyWriteFailed;
368 }
369
370 value = other;
371 }
372
373 if (mp.userType() == qMetaTypeId<QDBusVariant>())
374 value = QVariant::fromValue(QDBusVariant(value));
375
376 // the property type here should match
377 return mp.write(obj, value) ? PropertyWriteSuccess : PropertyWriteFailed;
378 }
379
qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode & node,const QDBusMessage & msg)380 QDBusMessage qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode &node,
381 const QDBusMessage &msg)
382 {
383 Q_ASSERT(msg.arguments().count() == 3);
384 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
385 "QDBusConnection: internal threading error",
386 "function called for an object that is in another thread!!");
387
388 QString interface_name = msg.arguments().at(0).toString();
389 QByteArray property_name = msg.arguments().at(1).toString().toUtf8();
390 QVariant value = qvariant_cast<QDBusVariant>(msg.arguments().at(2)).variant();
391
392 QDBusAdaptorConnector *connector;
393 if (node.flags & QDBusConnection::ExportAdaptors &&
394 (connector = qDBusFindAdaptorConnector(node.obj))) {
395
396 // find the class that implements interface_name or try until we've found the property
397 // in case of an empty interface
398 if (interface_name.isEmpty()) {
399 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
400 end = connector->adaptors.constEnd(); it != end; ++it) {
401 int status = writeProperty(it->adaptor, property_name, value);
402 if (status == PropertyNotFound)
403 continue;
404 return propertyWriteReply(msg, interface_name, property_name, status);
405 }
406 } else {
407 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
408 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
409 interface_name);
410 if (it != connector->adaptors.cend() && interface_name == QLatin1String(it->interface)) {
411 return propertyWriteReply(msg, interface_name, property_name,
412 writeProperty(it->adaptor, property_name, value));
413 }
414 }
415 }
416
417 if (node.flags & (QDBusConnection::ExportScriptableProperties |
418 QDBusConnection::ExportNonScriptableProperties)) {
419 // try the object itself
420 bool interfaceFound = true;
421 if (!interface_name.isEmpty())
422 interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);
423
424 if (interfaceFound) {
425 return propertyWriteReply(msg, interface_name, property_name,
426 writeProperty(node.obj, property_name, value, node.flags));
427 }
428 }
429
430 // the property was not found
431 if (!interface_name.isEmpty())
432 return interfaceNotFoundError(msg, interface_name);
433 return propertyWriteReply(msg, interface_name, property_name, PropertyNotFound);
434 }
435
436 // unite two QVariantMaps, but don't generate duplicate keys
operator +=(QVariantMap & lhs,const QVariantMap & rhs)437 static QVariantMap &operator+=(QVariantMap &lhs, const QVariantMap &rhs)
438 {
439 QVariantMap::ConstIterator it = rhs.constBegin(),
440 end = rhs.constEnd();
441 for ( ; it != end; ++it)
442 lhs.insert(it.key(), it.value());
443 return lhs;
444 }
445
readAllProperties(QObject * object,int flags)446 static QVariantMap readAllProperties(QObject *object, int flags)
447 {
448 QVariantMap result;
449 const QMetaObject *mo = object->metaObject();
450
451 // QObject has properties, so don't start from 0
452 for (int i = QObject::staticMetaObject.propertyCount(); i < mo->propertyCount(); ++i) {
453 QMetaProperty mp = mo->property(i);
454
455 // is it readable?
456 if (!mp.isReadable())
457 continue;
458
459 // is it a registered property?
460 int typeId = mp.userType();
461 if (!typeId)
462 continue;
463 const char *signature = QDBusMetaType::typeToSignature(typeId);
464 if (!signature)
465 continue;
466
467 // is this property visible from the outside?
468 if ((mp.isScriptable() && flags & QDBusConnection::ExportScriptableProperties) ||
469 (!mp.isScriptable() && flags & QDBusConnection::ExportNonScriptableProperties)) {
470 // yes, it's visible
471 QVariant value = mp.read(object);
472 if (value.isValid())
473 result.insert(QString::fromLatin1(mp.name()), value);
474 }
475 }
476
477 return result;
478 }
479
qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode & node,const QDBusMessage & msg)480 QDBusMessage qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode &node,
481 const QDBusMessage &msg)
482 {
483 Q_ASSERT(msg.arguments().count() == 1);
484 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
485 "QDBusConnection: internal threading error",
486 "function called for an object that is in another thread!!");
487
488 QString interface_name = msg.arguments().at(0).toString();
489
490 bool interfaceFound = false;
491 QVariantMap result;
492
493 QDBusAdaptorConnector *connector;
494 if (node.flags & QDBusConnection::ExportAdaptors &&
495 (connector = qDBusFindAdaptorConnector(node.obj))) {
496
497 if (interface_name.isEmpty()) {
498 // iterate over all interfaces
499 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
500 end = connector->adaptors.constEnd(); it != end; ++it) {
501 result += readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
502 }
503 } else {
504 // find the class that implements interface_name
505 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
506 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
507 interface_name);
508 if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
509 interfaceFound = true;
510 result = readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
511 }
512 }
513 }
514
515 if (node.flags & QDBusConnection::ExportAllProperties &&
516 (!interfaceFound || interface_name.isEmpty())) {
517 // try the object itself
518 result += readAllProperties(node.obj, node.flags);
519 interfaceFound = true;
520 }
521
522 if (!interfaceFound && !interface_name.isEmpty()) {
523 // the interface was not found
524 return interfaceNotFoundError(msg, interface_name);
525 }
526
527 return msg.createReply(QVariant::fromValue(result));
528 }
529
530 QT_END_NAMESPACE
531
532 #endif // QT_NO_DBUS
533