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
64QT_BEGIN_NAMESPACE
65
66// defined in qdbusxmlgenerator.cpp
67extern QString qDBusGenerateMetaObjectXml(QString interface, const QMetaObject *mo,
68 const QMetaObject *base, int flags);
69
70static 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
77static 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
102static 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
110static 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
126QString 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
203static 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
210static inline QDBusMessage
211propertyNotFoundError(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
221QDBusMessage 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
289enum PropertyWriteResult {
290 PropertyWriteSuccess = 0,
291 PropertyNotFound,
292 PropertyTypeMismatch,
293 PropertyReadOnly,
294 PropertyWriteFailed
295};
296
297static 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
326static 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 QMetaType id = mp.metaType();
352 if (!id.isValid()){
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.id() != QMetaType::QVariant && value.metaType() == QDBusMetaTypeId::argument()) {
360 // we have to demarshall before writing
361 QVariant other{QMetaType(id)};
362 if (!QDBusMetaType::demarshall(qvariant_cast<QDBusArgument>(value), other.metaType(), other.data())) {
363 qWarning("QDBusConnection: type `%s' (%d) is not registered with QtDBus. "
364 "Use qDBusRegisterMetaType to register it",
365 mp.typeName(), id.id());
366 return PropertyWriteFailed;
367 }
368
369 value = other;
370 }
371
372 if (mp.metaType() == QMetaType::fromType<QDBusVariant>())
373 value = QVariant::fromValue(QDBusVariant(value));
374
375 // the property type here should match
376 return mp.write(obj, value) ? PropertyWriteSuccess : PropertyWriteFailed;
377}
378
379QDBusMessage qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode &node,
380 const QDBusMessage &msg)
381{
382 Q_ASSERT(msg.arguments().count() == 3);
383 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
384 "QDBusConnection: internal threading error",
385 "function called for an object that is in another thread!!");
386
387 QString interface_name = msg.arguments().at(0).toString();
388 QByteArray property_name = msg.arguments().at(1).toString().toUtf8();
389 QVariant value = qvariant_cast<QDBusVariant>(msg.arguments().at(2)).variant();
390
391 QDBusAdaptorConnector *connector;
392 if (node.flags & QDBusConnection::ExportAdaptors &&
393 (connector = qDBusFindAdaptorConnector(node.obj))) {
394
395 // find the class that implements interface_name or try until we've found the property
396 // in case of an empty interface
397 if (interface_name.isEmpty()) {
398 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
399 end = connector->adaptors.constEnd(); it != end; ++it) {
400 int status = writeProperty(it->adaptor, property_name, value);
401 if (status == PropertyNotFound)
402 continue;
403 return propertyWriteReply(msg, interface_name, property_name, status);
404 }
405 } else {
406 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
407 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
408 interface_name);
409 if (it != connector->adaptors.cend() && interface_name == QLatin1String(it->interface)) {
410 return propertyWriteReply(msg, interface_name, property_name,
411 writeProperty(it->adaptor, property_name, value));
412 }
413 }
414 }
415
416 if (node.flags & (QDBusConnection::ExportScriptableProperties |
417 QDBusConnection::ExportNonScriptableProperties)) {
418 // try the object itself
419 bool interfaceFound = true;
420 if (!interface_name.isEmpty())
421 interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);
422
423 if (interfaceFound) {
424 return propertyWriteReply(msg, interface_name, property_name,
425 writeProperty(node.obj, property_name, value, node.flags));
426 }
427 }
428
429 // the property was not found
430 if (!interface_name.isEmpty())
431 return interfaceNotFoundError(msg, interface_name);
432 return propertyWriteReply(msg, interface_name, property_name, PropertyNotFound);
433}
434
435// unite two QVariantMaps, but don't generate duplicate keys
436static QVariantMap &operator+=(QVariantMap &lhs, const QVariantMap &rhs)
437{
438 QVariantMap::ConstIterator it = rhs.constBegin(),
439 end = rhs.constEnd();
440 for ( ; it != end; ++it)
441 lhs.insert(it.key(), it.value());
442 return lhs;
443}
444
445static QVariantMap readAllProperties(QObject *object, int flags)
446{
447 QVariantMap result;
448 const QMetaObject *mo = object->metaObject();
449
450 // QObject has properties, so don't start from 0
451 for (int i = QObject::staticMetaObject.propertyCount(); i < mo->propertyCount(); ++i) {
452 QMetaProperty mp = mo->property(i);
453
454 // is it readable?
455 if (!mp.isReadable())
456 continue;
457
458 // is it a registered property?
459 QMetaType type = mp.metaType();
460 if (!type.isValid())
461 continue;
462 const char *signature = QDBusMetaType::typeToSignature(type);
463 if (!signature)
464 continue;
465
466 // is this property visible from the outside?
467 if ((mp.isScriptable() && flags & QDBusConnection::ExportScriptableProperties) ||
468 (!mp.isScriptable() && flags & QDBusConnection::ExportNonScriptableProperties)) {
469 // yes, it's visible
470 QVariant value = mp.read(object);
471 if (value.isValid())
472 result.insert(QString::fromLatin1(mp.name()), value);
473 }
474 }
475
476 return result;
477}
478
479QDBusMessage qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode &node,
480 const QDBusMessage &msg)
481{
482 Q_ASSERT(msg.arguments().count() == 1);
483 Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
484 "QDBusConnection: internal threading error",
485 "function called for an object that is in another thread!!");
486
487 QString interface_name = msg.arguments().at(0).toString();
488
489 bool interfaceFound = false;
490 QVariantMap result;
491
492 QDBusAdaptorConnector *connector;
493 if (node.flags & QDBusConnection::ExportAdaptors &&
494 (connector = qDBusFindAdaptorConnector(node.obj))) {
495
496 if (interface_name.isEmpty()) {
497 // iterate over all interfaces
498 for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
499 end = connector->adaptors.constEnd(); it != end; ++it) {
500 result += readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
501 }
502 } else {
503 // find the class that implements interface_name
504 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
505 it = std::lower_bound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
506 interface_name);
507 if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
508 interfaceFound = true;
509 result = readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
510 }
511 }
512 }
513
514 if (node.flags & QDBusConnection::ExportAllProperties &&
515 (!interfaceFound || interface_name.isEmpty())) {
516 // try the object itself
517 result += readAllProperties(node.obj, node.flags);
518 interfaceFound = true;
519 }
520
521 if (!interfaceFound && !interface_name.isEmpty()) {
522 // the interface was not found
523 return interfaceNotFoundError(msg, interface_name);
524 }
525
526 return msg.createReply(QVariant::fromValue(result));
527}
528
529QT_END_NAMESPACE
530
531#endif // QT_NO_DBUS
532