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