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