1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtDBus module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qdbusconnection_p.h"
44 #include "qdbus_symbols_p.h"
45 #include <QtCore/qcoreapplication.h>
46 #include <QtCore/qmetaobject.h>
47 #include <QtCore/qstringlist.h>
48 #include <QtCore/qthread.h>
50 #include "qdbusabstractadaptor.h"
51 #include "qdbusabstractadaptor_p.h"
52 #include "qdbusconnection.h"
53 #include "qdbusextratypes.h"
54 #include "qdbusmessage.h"
55 #include "qdbusmetatype.h"
56 #include "qdbusmetatype_p.h"
57 #include "qdbusmessage_p.h"
58 #include "qdbusutil_p.h"
59 #include "qdbusvirtualobject.h"
67 // defined in qdbusxmlgenerator.cpp
68 extern QString qDBusGenerateMetaObjectXml(QString interface, const QMetaObject *mo,
69 const QMetaObject *base, int flags);
71 static const char introspectableInterfaceXml[] =
72 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
73 " <method name=\"Introspect\">\n"
74 " <arg name=\"xml_data\" type=\"s\" direction=\"out\"/>\n"
78 static const char propertiesInterfaceXml[] =
79 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
80 " <method name=\"Get\">\n"
81 " <arg name=\"interface_name\" type=\"s\" direction=\"in\"/>\n"
82 " <arg name=\"property_name\" type=\"s\" direction=\"in\"/>\n"
83 " <arg name=\"value\" type=\"v\" direction=\"out\"/>\n"
85 " <method name=\"Set\">\n"
86 " <arg name=\"interface_name\" type=\"s\" direction=\"in\"/>\n"
87 " <arg name=\"property_name\" type=\"s\" direction=\"in\"/>\n"
88 " <arg name=\"value\" type=\"v\" direction=\"in\"/>\n"
90 " <method name=\"GetAll\">\n"
91 " <arg name=\"interface_name\" type=\"s\" direction=\"in\"/>\n"
92 " <arg name=\"values\" type=\"a{sv}\" direction=\"out\"/>\n"
93 " <annotation name=\"org.qtproject.QtDBus.QtTypeName.Out0\" value=\"QVariantMap\"/>\n"
97 static const char peerInterfaceXml[] =
98 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
99 " <method name=\"Ping\"/>\n"
100 " <method name=\"GetMachineId\">\n"
101 " <arg name=\"machine_uuid\" type=\"s\" direction=\"out\"/>\n"
105 static QString generateSubObjectXml(QObject *object)
108 const QObjectList &objs = object->children();
109 QObjectList::ConstIterator it = objs.constBegin();
110 QObjectList::ConstIterator end = objs.constEnd();
111 for ( ; it != end; ++it) {
112 QString name = (*it)->objectName();
113 if (!name.isEmpty() && QDBusUtil::isValidPartOfObjectPath(name))
114 retval += QString::fromLatin1(" <node name=\"%1\"/>\n")
120 // declared as extern in qdbusconnection_p.h
122 QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node, const QString &path)
124 // object may be null
126 QString xml_data(QLatin1String(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE));
127 xml_data += QLatin1String("<node>\n");
130 Q_ASSERT_X(QThread::currentThread() == node.obj->thread(),
131 "QDBusConnection: internal threading error",
132 "function called for an object that is in another thread!!");
134 if (node.flags & (QDBusConnection::ExportScriptableContents
135 | QDBusConnection::ExportNonScriptableContents)) {
136 // create XML for the object itself
137 const QMetaObject *mo = node.obj->metaObject();
138 for ( ; mo != &QObject::staticMetaObject; mo = mo->superClass())
139 xml_data += qDBusGenerateMetaObjectXml(QString(), mo, mo->superClass(),
143 // does this object have adaptors?
144 QDBusAdaptorConnector *connector;
145 if (node.flags & QDBusConnection::ExportAdaptors &&
146 (connector = qDBusFindAdaptorConnector(node.obj))) {
148 // trasverse every adaptor in this object
149 QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin();
150 QDBusAdaptorConnector::AdaptorMap::ConstIterator end = connector->adaptors.constEnd();
151 for ( ; it != end; ++it) {
152 // add the interface:
153 QString ifaceXml = QDBusAbstractAdaptorPrivate::retrieveIntrospectionXml(it->adaptor);
154 if (ifaceXml.isEmpty()) {
155 // add the interface's contents:
156 ifaceXml += qDBusGenerateMetaObjectXml(QString::fromLatin1(it->interface),
157 it->adaptor->metaObject(),
158 &QDBusAbstractAdaptor::staticMetaObject,
159 QDBusConnection::ExportScriptableContents
160 | QDBusConnection::ExportNonScriptableContents);
162 QDBusAbstractAdaptorPrivate::saveIntrospectionXml(it->adaptor, ifaceXml);
165 xml_data += ifaceXml;
169 // is it a virtual node that handles introspection itself?
170 if (node.flags & QDBusConnectionPrivate::VirtualObject) {
171 xml_data += node.treeNode->introspect(path);
174 xml_data += QLatin1String( propertiesInterfaceXml );
177 xml_data += QLatin1String( introspectableInterfaceXml );
178 xml_data += QLatin1String( peerInterfaceXml );
180 if (node.flags & QDBusConnection::ExportChildObjects) {
181 xml_data += generateSubObjectXml(node.obj);
183 // generate from the object tree
184 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
185 node.children.constBegin();
186 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end =
187 node.children.constEnd();
188 for ( ; it != end; ++it)
189 if (it->obj || !it->children.isEmpty())
190 xml_data += QString::fromLatin1(" <node name=\"%1\"/>\n")
194 xml_data += QLatin1String("</node>\n");
198 // implement the D-Bus interface org.freedesktop.DBus.Properties
200 static inline QDBusMessage interfaceNotFoundError(const QDBusMessage &msg, const QString &interface_name)
202 return msg.createErrorReply(QDBusError::UnknownInterface,
203 QString::fromLatin1("Interface %1 was not found in object %2")
208 static inline QDBusMessage
209 propertyNotFoundError(const QDBusMessage &msg, const QString &interface_name, const QByteArray &property_name)
211 return msg.createErrorReply(QDBusError::UnknownProperty,
212 QString::fromLatin1("Property %1%2%3 was not found in object %4")
214 QString::fromLatin1(interface_name.isEmpty() ? "" : "."),
215 QString::fromLatin1(property_name),
219 QDBusMessage qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode &node,
220 const QDBusMessage &msg)
222 Q_ASSERT(msg.arguments().count() == 2);
223 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
224 "QDBusConnection: internal threading error",
225 "function called for an object that is in another thread!!");
227 QString interface_name = msg.arguments().at(0).toString();
228 QByteArray property_name = msg.arguments().at(1).toString().toUtf8();
230 QDBusAdaptorConnector *connector;
232 bool interfaceFound = false;
233 if (node.flags & QDBusConnection::ExportAdaptors &&
234 (connector = qDBusFindAdaptorConnector(node.obj))) {
236 // find the class that implements interface_name or try until we've found the property
237 // in case of an empty interface
238 if (interface_name.isEmpty()) {
239 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
240 end = connector->adaptors.constEnd(); it != end; ++it) {
241 const QMetaObject *mo = it->adaptor->metaObject();
242 int pidx = mo->indexOfProperty(property_name);
244 value = mo->property(pidx).read(it->adaptor);
249 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
250 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
252 if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
253 interfaceFound = true;
254 value = it->adaptor->property(property_name);
259 if (!interfaceFound && !value.isValid()
260 && node.flags & (QDBusConnection::ExportAllProperties |
261 QDBusConnection::ExportNonScriptableProperties)) {
262 // try the object itself
263 if (!interface_name.isEmpty())
264 interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);
266 if (interfaceFound) {
267 int pidx = node.obj->metaObject()->indexOfProperty(property_name);
269 QMetaProperty mp = node.obj->metaObject()->property(pidx);
270 if ((mp.isScriptable() && (node.flags & QDBusConnection::ExportScriptableProperties)) ||
271 (!mp.isScriptable() && (node.flags & QDBusConnection::ExportNonScriptableProperties)))
272 value = mp.read(node.obj);
277 if (!value.isValid()) {
278 // the property was not found
280 return interfaceNotFoundError(msg, interface_name);
281 return propertyNotFoundError(msg, interface_name, property_name);
284 return msg.createReply(QVariant::fromValue(QDBusVariant(value)));
287 enum PropertyWriteResult {
288 PropertyWriteSuccess = 0,
290 PropertyTypeMismatch,
295 static QDBusMessage propertyWriteReply(const QDBusMessage &msg, const QString &interface_name,
296 const QByteArray &property_name, int status)
299 case PropertyNotFound:
300 return propertyNotFoundError(msg, interface_name, property_name);
301 case PropertyTypeMismatch:
302 return msg.createErrorReply(QDBusError::InvalidArgs,
303 QString::fromLatin1("Invalid arguments for writing to property %1%2%3")
305 QString::fromLatin1(interface_name.isEmpty() ? "" : "."),
306 QString::fromLatin1(property_name)));
307 case PropertyReadOnly:
308 return msg.createErrorReply(QDBusError::PropertyReadOnly,
309 QString::fromLatin1("Property %1%2%3 is read-only")
311 QString::fromLatin1(interface_name.isEmpty() ? "" : "."),
312 QString::fromLatin1(property_name)));
313 case PropertyWriteFailed:
314 return msg.createErrorReply(QDBusError::InternalError,
315 QString::fromLatin1("Internal error"));
317 case PropertyWriteSuccess:
318 return msg.createReply();
320 Q_ASSERT_X(false, "", "Should not be reached");
321 return QDBusMessage();
324 static int writeProperty(QObject *obj, const QByteArray &property_name, QVariant value,
325 int propFlags = QDBusConnection::ExportAllProperties)
327 const QMetaObject *mo = obj->metaObject();
328 int pidx = mo->indexOfProperty(property_name);
330 // this object has no property by that name
331 return PropertyNotFound;
334 QMetaProperty mp = mo->property(pidx);
336 // check if this property is writable
337 if (!mp.isWritable())
338 return PropertyReadOnly;
340 // check if this property is exported
341 bool isScriptable = mp.isScriptable();
342 if (!(propFlags & QDBusConnection::ExportScriptableProperties) && isScriptable)
343 return PropertyNotFound;
344 if (!(propFlags & QDBusConnection::ExportNonScriptableProperties) && !isScriptable)
345 return PropertyNotFound;
347 // we found our property
348 // do we have the right type?
349 int id = mp.userType();
351 // type not registered or invalid / void?
352 qWarning("QDBusConnection: Unable to handle unregistered datatype '%s' for property '%s::%s'",
353 mp.typeName(), mo->className(), property_name.constData());
354 return PropertyWriteFailed;
357 if (id != QMetaType::QVariant && value.userType() == QDBusMetaTypeId::argument()) {
358 // we have to demarshall before writing
360 QVariant other(id, null);
361 if (!QDBusMetaType::demarshall(qvariant_cast<QDBusArgument>(value), id, other.data())) {
362 qWarning("QDBusConnection: type `%s' (%d) is not registered with QtDBus. "
363 "Use qDBusRegisterMetaType to register it",
365 return PropertyWriteFailed;
371 // the property type here should match
372 return mp.write(obj, value) ? PropertyWriteSuccess : PropertyWriteFailed;
375 QDBusMessage qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode &node,
376 const QDBusMessage &msg)
378 Q_ASSERT(msg.arguments().count() == 3);
379 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
380 "QDBusConnection: internal threading error",
381 "function called for an object that is in another thread!!");
383 QString interface_name = msg.arguments().at(0).toString();
384 QByteArray property_name = msg.arguments().at(1).toString().toUtf8();
385 QVariant value = qvariant_cast<QDBusVariant>(msg.arguments().at(2)).variant();
387 QDBusAdaptorConnector *connector;
388 if (node.flags & QDBusConnection::ExportAdaptors &&
389 (connector = qDBusFindAdaptorConnector(node.obj))) {
391 // find the class that implements interface_name or try until we've found the property
392 // in case of an empty interface
393 if (interface_name.isEmpty()) {
394 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
395 end = connector->adaptors.constEnd(); it != end; ++it) {
396 int status = writeProperty(it->adaptor, property_name, value);
397 if (status == PropertyNotFound)
399 return propertyWriteReply(msg, interface_name, property_name, status);
402 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
403 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
405 if (it != connector->adaptors.end() && interface_name == QLatin1String(it->interface)) {
406 return propertyWriteReply(msg, interface_name, property_name,
407 writeProperty(it->adaptor, property_name, value));
412 if (node.flags & (QDBusConnection::ExportScriptableProperties |
413 QDBusConnection::ExportNonScriptableProperties)) {
414 // try the object itself
415 bool interfaceFound = true;
416 if (!interface_name.isEmpty())
417 interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);
419 if (interfaceFound) {
420 return propertyWriteReply(msg, interface_name, property_name,
421 writeProperty(node.obj, property_name, value, node.flags));
425 // the property was not found
426 if (!interface_name.isEmpty())
427 return interfaceNotFoundError(msg, interface_name);
428 return propertyWriteReply(msg, interface_name, property_name, PropertyNotFound);
431 // unite two QVariantMaps, but don't generate duplicate keys
432 static QVariantMap &operator+=(QVariantMap &lhs, const QVariantMap &rhs)
434 QVariantMap::ConstIterator it = rhs.constBegin(),
435 end = rhs.constEnd();
436 for ( ; it != end; ++it)
437 lhs.insert(it.key(), it.value());
441 static QVariantMap readAllProperties(QObject *object, int flags)
444 const QMetaObject *mo = object->metaObject();
446 // QObject has properties, so don't start from 0
447 for (int i = QObject::staticMetaObject.propertyCount(); i < mo->propertyCount(); ++i) {
448 QMetaProperty mp = mo->property(i);
451 if (!mp.isReadable())
454 // is it a registered property?
455 int typeId = mp.userType();
458 const char *signature = QDBusMetaType::typeToSignature(typeId);
462 // is this property visible from the outside?
463 if ((mp.isScriptable() && flags & QDBusConnection::ExportScriptableProperties) ||
464 (!mp.isScriptable() && flags & QDBusConnection::ExportNonScriptableProperties)) {
466 QVariant value = mp.read(object);
468 result.insert(QString::fromLatin1(mp.name()), value);
475 QDBusMessage qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode &node,
476 const QDBusMessage &msg)
478 Q_ASSERT(msg.arguments().count() == 1);
479 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
480 "QDBusConnection: internal threading error",
481 "function called for an object that is in another thread!!");
483 QString interface_name = msg.arguments().at(0).toString();
485 bool interfaceFound = false;
488 QDBusAdaptorConnector *connector;
489 if (node.flags & QDBusConnection::ExportAdaptors &&
490 (connector = qDBusFindAdaptorConnector(node.obj))) {
492 if (interface_name.isEmpty()) {
493 // iterate over all interfaces
494 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
495 end = connector->adaptors.constEnd(); it != end; ++it) {
496 result += readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
499 // find the class that implements interface_name
500 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
501 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
503 if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
504 interfaceFound = true;
505 result = readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
510 if (node.flags & QDBusConnection::ExportAllProperties &&
511 (!interfaceFound || interface_name.isEmpty())) {
512 // try the object itself
513 result += readAllProperties(node.obj, node.flags);
514 interfaceFound = true;
517 if (!interfaceFound && !interface_name.isEmpty()) {
518 // the interface was not found
519 return interfaceNotFoundError(msg, interface_name);
522 return msg.createReply(QVariant::fromValue(result));