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