Finish cleaning up com.trolltech -> org.qtproject in QtDBus
[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::InvalidArgs,
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     PropertyWriteFailed
281 };
282
283 static QDBusMessage propertyWriteReply(const QDBusMessage &msg, const QString &interface_name,
284                                        const QByteArray &property_name, int status)
285 {
286     switch (status) {
287     case PropertyNotFound:
288         return propertyNotFoundError(msg, interface_name, property_name);
289     case PropertyTypeMismatch:
290         return msg.createErrorReply(QDBusError::InvalidArgs,
291                                     QString::fromLatin1("Invalid arguments for writing to property %1%2%3")
292                                     .arg(interface_name,
293                                          QString::fromLatin1(interface_name.isEmpty() ? "" : "."),
294                                          QString::fromLatin1(property_name)));
295     case PropertyWriteFailed:
296         return msg.createErrorReply(QDBusError::InternalError,
297                                     QString::fromLatin1("Internal error"));
298
299     case PropertyWriteSuccess:
300         return msg.createReply();
301     }
302     Q_ASSERT_X(false, "", "Should not be reached");
303     return QDBusMessage();
304 }
305
306 static int writeProperty(QObject *obj, const QByteArray &property_name, QVariant value,
307                          int propFlags = QDBusConnection::ExportAllProperties)
308 {
309     const QMetaObject *mo = obj->metaObject();
310     int pidx = mo->indexOfProperty(property_name);
311     if (pidx == -1) {
312         // this object has no property by that name
313         return PropertyNotFound;
314     }
315
316     QMetaProperty mp = mo->property(pidx);
317
318     // check if this property is exported
319     bool isScriptable = mp.isScriptable();
320     if (!(propFlags & QDBusConnection::ExportScriptableProperties) && isScriptable)
321         return PropertyNotFound;
322     if (!(propFlags & QDBusConnection::ExportNonScriptableProperties) && !isScriptable)
323         return PropertyNotFound;
324
325     // we found our property
326     // do we have the right type?
327     int id = mp.userType();
328     if (!id){
329         // type not registered or invalid / void?
330         qWarning("QDBusConnection: Unable to handle unregistered datatype '%s' for property '%s::%s'",
331                  mp.typeName(), mo->className(), property_name.constData());
332         return PropertyWriteFailed;
333     }
334
335     if (id != QMetaType::QVariant && value.userType() == QDBusMetaTypeId::argument) {
336         // we have to demarshall before writing
337         void *null = 0;
338         QVariant other(id, null);
339         if (!QDBusMetaType::demarshall(qvariant_cast<QDBusArgument>(value), id, other.data())) {
340             qWarning("QDBusConnection: type `%s' (%d) is not registered with QtDBus. "
341                      "Use qDBusRegisterMetaType to register it",
342                      mp.typeName(), id);
343             return PropertyWriteFailed;
344         }
345
346         value = other;
347     }
348
349     // the property type here should match
350     return mp.write(obj, value) ? PropertyWriteSuccess : PropertyWriteFailed;
351 }
352
353 QDBusMessage qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode &node,
354                               const QDBusMessage &msg)
355 {
356     Q_ASSERT(msg.arguments().count() == 3);
357     Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
358                "QDBusConnection: internal threading error",
359                "function called for an object that is in another thread!!");
360
361     QString interface_name = msg.arguments().at(0).toString();
362     QByteArray property_name = msg.arguments().at(1).toString().toUtf8();
363     QVariant value = qvariant_cast<QDBusVariant>(msg.arguments().at(2)).variant();
364
365     QDBusAdaptorConnector *connector;
366     if (node.flags & QDBusConnection::ExportAdaptors &&
367         (connector = qDBusFindAdaptorConnector(node.obj))) {
368
369         // find the class that implements interface_name or try until we've found the property
370         // in case of an empty interface
371         if (interface_name.isEmpty()) {
372             for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
373                  end = connector->adaptors.constEnd(); it != end; ++it) {
374                 int status = writeProperty(it->adaptor, property_name, value);
375                 if (status == PropertyNotFound)
376                     continue;
377                 return propertyWriteReply(msg, interface_name, property_name, status);
378             }
379         } else {
380             QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
381             it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
382                              interface_name);
383             if (it != connector->adaptors.end() && interface_name == QLatin1String(it->interface)) {
384                 return propertyWriteReply(msg, interface_name, property_name,
385                                           writeProperty(it->adaptor, property_name, value));
386             }
387         }
388     }
389
390     if (node.flags & (QDBusConnection::ExportScriptableProperties |
391                       QDBusConnection::ExportNonScriptableProperties)) {
392         // try the object itself
393         bool interfaceFound = true;
394         if (!interface_name.isEmpty())
395             interfaceFound = qDBusInterfaceInObject(node.obj, interface_name);
396
397         if (interfaceFound) {
398             return propertyWriteReply(msg, interface_name, property_name,
399                                       writeProperty(node.obj, property_name, value, node.flags));
400         }
401     }
402
403     // the property was not found
404     if (!interface_name.isEmpty())
405         return interfaceNotFoundError(msg, interface_name);
406     return propertyWriteReply(msg, interface_name, property_name, PropertyNotFound);
407 }
408
409 // unite two QVariantMaps, but don't generate duplicate keys
410 static QVariantMap &operator+=(QVariantMap &lhs, const QVariantMap &rhs)
411 {
412     QVariantMap::ConstIterator it = rhs.constBegin(),
413                               end = rhs.constEnd();
414     for ( ; it != end; ++it)
415         lhs.insert(it.key(), it.value());
416     return lhs;
417 }
418
419 static QVariantMap readAllProperties(QObject *object, int flags)
420 {
421     QVariantMap result;
422     const QMetaObject *mo = object->metaObject();
423
424     // QObject has properties, so don't start from 0
425     for (int i = QObject::staticMetaObject.propertyCount(); i < mo->propertyCount(); ++i) {
426         QMetaProperty mp = mo->property(i);
427
428         // is it readable?
429         if (!mp.isReadable())
430             continue;
431
432         // is it a registered property?
433         int typeId = mp.userType();
434         if (!typeId)
435             continue;
436         const char *signature = QDBusMetaType::typeToSignature(typeId);
437         if (!signature)
438             continue;
439
440         // is this property visible from the outside?
441         if ((mp.isScriptable() && flags & QDBusConnection::ExportScriptableProperties) ||
442             (!mp.isScriptable() && flags & QDBusConnection::ExportNonScriptableProperties)) {
443             // yes, it's visible
444             QVariant value = mp.read(object);
445             if (value.isValid())
446                 result.insert(QString::fromLatin1(mp.name()), value);
447         }
448     }
449
450     return result;
451 }
452
453 QDBusMessage qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode &node,
454                                  const QDBusMessage &msg)
455 {
456     Q_ASSERT(msg.arguments().count() == 1);
457     Q_ASSERT_X(!node.obj || QThread::currentThread() == node.obj->thread(),
458                "QDBusConnection: internal threading error",
459                "function called for an object that is in another thread!!");
460
461     QString interface_name = msg.arguments().at(0).toString();
462
463     bool interfaceFound = false;
464     QVariantMap result;
465
466     QDBusAdaptorConnector *connector;
467     if (node.flags & QDBusConnection::ExportAdaptors &&
468         (connector = qDBusFindAdaptorConnector(node.obj))) {
469
470         if (interface_name.isEmpty()) {
471             // iterate over all interfaces
472             for (QDBusAdaptorConnector::AdaptorMap::ConstIterator it = connector->adaptors.constBegin(),
473                  end = connector->adaptors.constEnd(); it != end; ++it) {
474                 result += readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
475             }
476         } else {
477             // find the class that implements interface_name
478             QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
479             it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
480                              interface_name);
481             if (it != connector->adaptors.constEnd() && interface_name == QLatin1String(it->interface)) {
482                 interfaceFound = true;
483                 result = readAllProperties(it->adaptor, QDBusConnection::ExportAllProperties);
484             }
485         }
486     }
487
488     if (node.flags & QDBusConnection::ExportAllProperties &&
489         (!interfaceFound || interface_name.isEmpty())) {
490         // try the object itself
491         result += readAllProperties(node.obj, node.flags);
492         interfaceFound = true;
493     }
494
495     if (!interfaceFound && !interface_name.isEmpty()) {
496         // the interface was not found
497         return interfaceNotFoundError(msg, interface_name);
498     }
499
500     return msg.createReply(QVariant::fromValue(result));
501 }
502
503 QT_END_NAMESPACE
504
505 #endif // QT_NO_DBUS