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