1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtDBus module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 #include <qcoreapplication.h>
44 #include <qmetaobject.h>
46 #include <qsocketnotifier.h>
47 #include <qstringlist.h>
51 #include "qdbusargument.h"
52 #include "qdbusconnection_p.h"
53 #include "qdbusinterface_p.h"
54 #include "qdbusmessage.h"
55 #include "qdbusmetatype.h"
56 #include "qdbusmetatype_p.h"
57 #include "qdbusabstractadaptor.h"
58 #include "qdbusabstractadaptor_p.h"
59 #include "qdbusutil_p.h"
60 #include "qdbusmessage_p.h"
61 #include "qdbuscontext_p.h"
62 #include "qdbuspendingcall_p.h"
63 #include "qdbusintegrator_p.h"
65 #include "qdbusthreaddebug_p.h"
71 static bool isDebugging;
72 #define qDBusDebug if (!::isDebugging); else qDebug
74 Q_GLOBAL_STATIC_WITH_ARGS(const QString, orgFreedesktopDBusString, (QLatin1String(DBUS_SERVICE_DBUS)))
76 static inline QString dbusServiceString()
77 { return *orgFreedesktopDBusString(); }
78 static inline QString dbusInterfaceString()
80 // it's the same string, but just be sure
81 Q_ASSERT(*orgFreedesktopDBusString() == QLatin1String(DBUS_INTERFACE_DBUS));
82 return *orgFreedesktopDBusString();
85 static inline QDebug operator<<(QDebug dbg, const QThread *th)
87 dbg.nospace() << "QThread(ptr=" << (void*)th;
88 if (th && !th->objectName().isEmpty())
89 dbg.nospace() << ", name=" << th->objectName();
94 #if QDBUS_THREAD_DEBUG
95 static inline QDebug operator<<(QDebug dbg, const QDBusConnectionPrivate *conn)
97 dbg.nospace() << "QDBusConnection("
98 << "ptr=" << (void*)conn
99 << ", name=" << conn->name
100 << ", baseService=" << conn->baseService
102 if (conn->thread() == QThread::currentThread())
103 dbg.nospace() << "same thread";
105 dbg.nospace() << conn->thread();
106 dbg.nospace() << ')';
110 Q_AUTOTEST_EXPORT void qdbusDefaultThreadDebug(int action, int condition, QDBusConnectionPrivate *conn)
112 qDBusDebug() << QThread::currentThread()
113 << "QtDBus threading action" << action
114 << (condition == QDBusLockerBase::BeforeLock ? "before lock" :
115 condition == QDBusLockerBase::AfterLock ? "after lock" :
116 condition == QDBusLockerBase::BeforeUnlock ? "before unlock" :
117 condition == QDBusLockerBase::AfterUnlock ? "after unlock" :
118 condition == QDBusLockerBase::BeforePost ? "before event posting" :
119 condition == QDBusLockerBase::AfterPost ? "after event posting" :
120 condition == QDBusLockerBase::BeforeDeliver ? "before event delivery" :
121 condition == QDBusLockerBase::AfterDeliver ? "after event delivery" :
122 condition == QDBusLockerBase::BeforeAcquire ? "before acquire" :
123 condition == QDBusLockerBase::AfterAcquire ? "after acquire" :
124 condition == QDBusLockerBase::BeforeRelease ? "before release" :
125 condition == QDBusLockerBase::AfterRelease ? "after release" :
127 << "in connection" << conn;
129 Q_AUTOTEST_EXPORT qdbusThreadDebugFunc qdbusThreadDebug = 0;
132 typedef void (*QDBusSpyHook)(const QDBusMessage&);
133 typedef QVarLengthArray<QDBusSpyHook, 4> QDBusSpyHookList;
134 Q_GLOBAL_STATIC(QDBusSpyHookList, qDBusSpyHookList)
138 // libdbus-1 callbacks
140 static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms);
141 static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
146 // qDebug("addTimeout %d", q_dbus_timeout_get_interval(timeout));
148 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
150 if (!q_dbus_timeout_get_enabled(timeout))
153 QDBusWatchAndTimeoutLocker locker(AddTimeoutAction, d);
154 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
156 return qDBusRealAddTimeout(d, timeout, q_dbus_timeout_get_interval(timeout));
158 // wrong thread: sync back
159 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
160 ev->subtype = QDBusConnectionCallbackEvent::AddTimeout;
161 d->timeoutsPendingAdd.append(qMakePair(timeout, q_dbus_timeout_get_interval(timeout)));
162 d->postEventToThread(AddTimeoutAction, d, ev);
167 static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms)
169 Q_ASSERT(d->timeouts.keys(timeout).isEmpty());
171 int timerId = d->startTimer(ms);
175 d->timeouts[timerId] = timeout;
179 static void qDBusRemoveTimeout(DBusTimeout *timeout, void *data)
184 // qDebug("removeTimeout");
186 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
188 QDBusWatchAndTimeoutLocker locker(RemoveTimeoutAction, d);
190 // is it pending addition?
191 QDBusConnectionPrivate::PendingTimeoutList::iterator pit = d->timeoutsPendingAdd.begin();
192 while (pit != d->timeoutsPendingAdd.end()) {
193 if (pit->first == timeout)
194 pit = d->timeoutsPendingAdd.erase(pit);
199 // is it a running timer?
200 bool correctThread = QCoreApplication::instance() && QThread::currentThread() == d->thread();
201 QDBusConnectionPrivate::TimeoutHash::iterator it = d->timeouts.begin();
202 while (it != d->timeouts.end()) {
203 if (it.value() == timeout) {
206 d->killTimer(it.key());
208 // incorrect thread or no application, post an event for later
209 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
210 ev->subtype = QDBusConnectionCallbackEvent::KillTimer;
211 ev->timerId = it.key();
212 d->postEventToThread(KillTimerAction, d, ev);
214 it = d->timeouts.erase(it);
222 static void qDBusToggleTimeout(DBusTimeout *timeout, void *data)
227 //qDebug("ToggleTimeout");
229 qDBusRemoveTimeout(timeout, data);
230 qDBusAddTimeout(timeout, data);
233 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd);
234 static dbus_bool_t qDBusAddWatch(DBusWatch *watch, void *data)
239 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
241 int flags = q_dbus_watch_get_flags(watch);
242 int fd = q_dbus_watch_get_fd(watch);
244 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
245 return qDBusRealAddWatch(d, watch, flags, fd);
247 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
248 ev->subtype = QDBusConnectionCallbackEvent::AddWatch;
252 d->postEventToThread(AddWatchAction, d, ev);
257 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd)
259 QDBusConnectionPrivate::Watcher watcher;
261 QDBusWatchAndTimeoutLocker locker(AddWatchAction, d);
262 if (flags & DBUS_WATCH_READABLE) {
263 //qDebug("addReadWatch %d", fd);
264 watcher.watch = watch;
265 if (QCoreApplication::instance()) {
266 watcher.read = new QSocketNotifier(fd, QSocketNotifier::Read, d);
267 watcher.read->setEnabled(q_dbus_watch_get_enabled(watch));
268 d->connect(watcher.read, SIGNAL(activated(int)), SLOT(socketRead(int)));
271 if (flags & DBUS_WATCH_WRITABLE) {
272 //qDebug("addWriteWatch %d", fd);
273 watcher.watch = watch;
274 if (QCoreApplication::instance()) {
275 watcher.write = new QSocketNotifier(fd, QSocketNotifier::Write, d);
276 watcher.write->setEnabled(q_dbus_watch_get_enabled(watch));
277 d->connect(watcher.write, SIGNAL(activated(int)), SLOT(socketWrite(int)));
280 d->watchers.insertMulti(fd, watcher);
285 static void qDBusRemoveWatch(DBusWatch *watch, void *data)
290 //qDebug("remove watch");
292 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
293 int fd = q_dbus_watch_get_fd(watch);
295 QDBusWatchAndTimeoutLocker locker(RemoveWatchAction, d);
296 QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
297 while (i != d->watchers.end() && i.key() == fd) {
298 if (i.value().watch == watch) {
299 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
300 // correct thread, delete the socket notifiers
301 delete i.value().read;
302 delete i.value().write;
304 // incorrect thread or no application, use delete later
306 i->read->deleteLater();
308 i->write->deleteLater();
310 i = d->watchers.erase(i);
317 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd);
318 static void qDBusToggleWatch(DBusWatch *watch, void *data)
323 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
324 int fd = q_dbus_watch_get_fd(watch);
326 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
327 qDBusRealToggleWatch(d, watch, fd);
329 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
330 ev->subtype = QDBusConnectionCallbackEvent::ToggleWatch;
333 d->postEventToThread(ToggleWatchAction, d, ev);
337 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd)
339 QDBusWatchAndTimeoutLocker locker(ToggleWatchAction, d);
341 QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
342 while (i != d->watchers.end() && i.key() == fd) {
343 if (i.value().watch == watch) {
344 bool enabled = q_dbus_watch_get_enabled(watch);
345 int flags = q_dbus_watch_get_flags(watch);
347 //qDebug("toggle watch %d to %d (write: %d, read: %d)", q_dbus_watch_get_fd(watch), enabled, flags & DBUS_WATCH_WRITABLE, flags & DBUS_WATCH_READABLE);
349 if (flags & DBUS_WATCH_READABLE && i.value().read)
350 i.value().read->setEnabled(enabled);
351 if (flags & DBUS_WATCH_WRITABLE && i.value().write)
352 i.value().write->setEnabled(enabled);
359 static void qDBusUpdateDispatchStatus(DBusConnection *connection, DBusDispatchStatus new_status, void *data)
361 Q_ASSERT(connection);
362 Q_UNUSED(connection);
363 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
365 static int slotId; // 0 is QObject::deleteLater()
367 // it's ok to do this: there's no race condition because the store is atomic
368 // and we always set to the same value
369 slotId = QDBusConnectionPrivate::staticMetaObject.indexOfSlot("doDispatch()");
372 //qDBusDebug() << "Updating dispatcher status" << slotId;
373 if (new_status == DBUS_DISPATCH_DATA_REMAINS)
374 QDBusConnectionPrivate::staticMetaObject.method(slotId).
375 invoke(d, Qt::QueuedConnection);
378 static void qDBusNewConnection(DBusServer *server, DBusConnection *connection, void *data)
380 // ### We may want to separate the server from the QDBusConnectionPrivate
381 Q_ASSERT(server); Q_UNUSED(server);
382 Q_ASSERT(connection);
385 // keep the connection alive
386 q_dbus_connection_ref(connection);
387 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
389 // setPeer does the error handling for us
390 QDBusErrorInternal error;
391 d->setPeer(connection, error);
393 QDBusConnection retval = QDBusConnectionPrivate::q(d);
395 // make QDBusServer emit the newConnection signal
396 d->serverConnection(retval);
401 static QByteArray buildMatchRule(const QString &service,
402 const QString &objectPath, const QString &interface,
403 const QString &member, const QStringList &argMatch, const QString & /*signature*/)
405 QString result = QLatin1String("type='signal',");
406 QString keyValue = QLatin1String("%1='%2',");
408 if (!service.isEmpty())
409 result += keyValue.arg(QLatin1String("sender"), service);
410 if (!objectPath.isEmpty())
411 result += keyValue.arg(QLatin1String("path"), objectPath);
412 if (!interface.isEmpty())
413 result += keyValue.arg(QLatin1String("interface"), interface);
414 if (!member.isEmpty())
415 result += keyValue.arg(QLatin1String("member"), member);
417 // add the argument string-matching now
418 if (!argMatch.isEmpty()) {
419 keyValue = QLatin1String("arg%1='%2',");
420 for (int i = 0; i < argMatch.count(); ++i)
421 if (!argMatch.at(i).isNull())
422 result += keyValue.arg(i).arg(argMatch.at(i));
425 result.chop(1); // remove ending comma
426 return result.toLatin1();
429 static bool findObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
430 const QString &fullpath, int &usedLength,
431 QDBusConnectionPrivate::ObjectTreeNode &result)
433 if (!fullpath.compare(QLatin1String("/")) && root->obj) {
439 int length = fullpath.length();
440 if (fullpath.at(0) == QLatin1Char('/'))
443 // walk the object tree
444 const QDBusConnectionPrivate::ObjectTreeNode *node = root;
445 while (start < length && node && !(node->flags & QDBusConnection::ExportChildObjects)) {
446 int end = fullpath.indexOf(QLatin1Char('/'), start);
447 end = (end == -1 ? length : end);
448 QStringRef pathComponent(&fullpath, start, end - start);
450 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
451 qLowerBound(node->children.constBegin(), node->children.constEnd(), pathComponent);
452 if (it != node->children.constEnd() && it->name == pathComponent)
462 usedLength = (start > length ? length : start);
464 if (node->obj || !node->children.isEmpty())
467 // there really is no object here
468 // we're just looking at an unused space in the QVector
474 static QObject *findChildObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
475 const QString &fullpath, int start)
477 int length = fullpath.length();
479 // any object in the tree can tell us to switch to its own object tree:
480 const QDBusConnectionPrivate::ObjectTreeNode *node = root;
481 if (node && node->flags & QDBusConnection::ExportChildObjects) {
482 QObject *obj = node->obj;
486 // we're at the correct level
489 int pos = fullpath.indexOf(QLatin1Char('/'), start);
490 pos = (pos == -1 ? length : pos);
491 QStringRef pathComponent(&fullpath, start, pos - start);
493 const QObjectList children = obj->children();
495 // find a child with the proper name
497 QObjectList::ConstIterator it = children.constBegin();
498 QObjectList::ConstIterator end = children.constEnd();
499 for ( ; it != end; ++it)
500 if ((*it)->objectName() == pathComponent) {
517 static bool shouldWatchService(const QString &service)
519 return !service.isEmpty() && !service.startsWith(QLatin1Char(':'));
522 extern Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook);
523 void qDBusAddSpyHook(QDBusSpyHook hook)
525 qDBusSpyHookList()->append(hook);
529 static DBusHandlerResult
530 qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
533 Q_UNUSED(connection);
534 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
535 if (d->mode == QDBusConnectionPrivate::InvalidMode)
536 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
538 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(message, d->capabilities);
539 qDBusDebug() << d << "got message (signal):" << amsg;
541 return d->handleMessage(amsg) ?
542 DBUS_HANDLER_RESULT_HANDLED :
543 DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
547 bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
549 const QDBusSpyHookList *list = qDBusSpyHookList();
550 for (int i = 0; i < list->size(); ++i) {
551 qDBusDebug() << "calling the message spy hook";
558 switch (amsg.type()) {
559 case QDBusMessage::SignalMessage:
561 // if there are any other filters in this DBusConnection,
562 // let them see the signal too
564 case QDBusMessage::MethodCallMessage:
565 handleObjectCall(amsg);
567 case QDBusMessage::ReplyMessage:
568 case QDBusMessage::ErrorMessage:
569 case QDBusMessage::InvalidMessage:
570 return false; // we don't handle those here
576 static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode &haystack)
578 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it = haystack.children.begin();
579 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator end = haystack.children.end();
580 for ( ; it != end; ++it)
581 huntAndDestroy(needle, *it);
583 if (needle == haystack.obj) {
589 static void huntAndEmit(DBusConnection *connection, DBusMessage *msg,
590 QObject *needle, const QDBusConnectionPrivate::ObjectTreeNode &haystack,
591 bool isScriptable, bool isAdaptor, const QString &path = QString())
593 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it = haystack.children.constBegin();
594 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end = haystack.children.constEnd();
595 for ( ; it != end; ++it)
596 huntAndEmit(connection, msg, needle, *it, isScriptable, isAdaptor, path + QLatin1Char('/') + it->name);
598 if (needle == haystack.obj) {
599 // is this a signal we should relay?
600 if (isAdaptor && (haystack.flags & QDBusConnection::ExportAdaptors) == 0)
601 return; // no: it comes from an adaptor and we're not exporting adaptors
602 else if (!isAdaptor) {
603 int mask = isScriptable
604 ? QDBusConnection::ExportScriptableSignals
605 : QDBusConnection::ExportNonScriptableSignals;
606 if ((haystack.flags & mask) == 0)
607 return; // signal was not exported
610 QByteArray p = path.toLatin1();
613 qDBusDebug() << QThread::currentThread() << "emitting signal at" << p;
614 DBusMessage *msg2 = q_dbus_message_copy(msg);
615 q_dbus_message_set_path(msg2, p);
616 q_dbus_connection_send(connection, msg2, 0);
617 q_dbus_message_unref(msg2);
621 static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
622 const QString &signature_, QList<int>& metaTypes)
624 QByteArray msgSignature = signature_.toLatin1();
626 for (int idx = mo->methodCount() - 1 ; idx >= QObject::staticMetaObject.methodCount(); --idx) {
627 QMetaMethod mm = mo->method(idx);
630 if (mm.access() != QMetaMethod::Public)
634 if (mm.methodType() != QMetaMethod::Slot && mm.methodType() != QMetaMethod::Method)
638 QByteArray slotname = mm.signature();
639 int paren = slotname.indexOf('(');
640 if (paren != name.length() || !slotname.startsWith(name))
643 int returnType = qDBusNameToTypeId(mm.typeName());
644 bool isAsync = qDBusCheckAsyncTag(mm.tag());
645 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
647 // consistency check:
648 if (isAsync && returnType != QMetaType::Void)
651 int inputCount = qDBusParametersForMethod(mm, metaTypes);
652 if (inputCount == -1)
653 continue; // problem parsing
655 metaTypes[0] = returnType;
656 bool hasMessage = false;
657 if (inputCount > 0 &&
658 metaTypes.at(inputCount) == QDBusMetaTypeId::message) {
659 // "no input parameters" is allowed as long as the message meta type is there
664 // try to match the parameters
666 QByteArray reconstructedSignature;
667 for (i = 1; i <= inputCount; ++i) {
668 const char *typeSignature = QDBusMetaType::typeToSignature( metaTypes.at(i) );
672 reconstructedSignature += typeSignature;
673 if (!msgSignature.startsWith(reconstructedSignature))
677 if (reconstructedSignature != msgSignature)
678 continue; // we didn't match them all
683 // make sure that the output parameters have signatures too
684 if (returnType != 0 && QDBusMetaType::typeToSignature(returnType) == 0)
688 for (int j = i; ok && j < metaTypes.count(); ++j)
689 if (QDBusMetaType::typeToSignature(metaTypes.at(i)) == 0)
694 // consistency check:
695 if (isAsync && metaTypes.count() > i + 1)
698 if (mm.methodType() == QMetaMethod::Slot) {
699 if (isScriptable && (flags & QDBusConnection::ExportScriptableSlots) == 0)
700 continue; // scriptable slots not exported
701 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableSlots) == 0)
702 continue; // non-scriptable slots not exported
704 if (isScriptable && (flags & QDBusConnection::ExportScriptableInvokables) == 0)
705 continue; // scriptable invokables not exported
706 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableInvokables) == 0)
707 continue; // non-scriptable invokables not exported
710 // if we got here, this slot matched
718 static QDBusCallDeliveryEvent * const DIRECT_DELIVERY = (QDBusCallDeliveryEvent *)1;
720 QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
721 QObject *object, int idx,
722 const QList<int> &metaTypes,
723 const QDBusMessage &msg)
728 int n = metaTypes.count() - 1;
729 if (metaTypes[n] == QDBusMetaTypeId::message)
732 if (msg.arguments().count() < n)
733 return 0; // too few arguments
735 // check that types match
736 for (int i = 0; i < n; ++i)
737 if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() &&
738 msg.arguments().at(i).userType() != qMetaTypeId<QDBusArgument>())
739 return 0; // no match
742 // prepare for the call
743 if (target == object)
744 return DIRECT_DELIVERY;
745 return new QDBusCallDeliveryEvent(QDBusConnection(target), idx, target, msg, metaTypes);
748 void QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
749 const QDBusMessage &msg)
751 // This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
752 // that was received from D-Bus
754 // Signals are delivered to slots if the parameters match
755 // Slots can have less parameters than there are on the message
756 // Slots can optionally have one final parameter that is a QDBusMessage
757 // Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
758 QDBusCallDeliveryEvent *call = prepareReply(this, hook.obj, hook.midx, hook.params, msg);
759 if (call == DIRECT_DELIVERY) {
760 // short-circuit delivery
761 Q_ASSERT(this == hook.obj);
762 deliverCall(this, 0, msg, hook.params, hook.midx);
766 postEventToThread(ActivateSignalAction, hook.obj, call);
769 bool QDBusConnectionPrivate::activateCall(QObject* object, int flags, const QDBusMessage &msg)
771 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call
772 // to a slot on the object.
774 // The call is delivered to the first slot that matches the following conditions:
775 // - has the same name as the message's target member
776 // - ALL of the message's types are found in slot's parameter list
777 // - optionally has one more parameter of type QDBusMessage
778 // If none match, then the slot of the same name as the message target and with
779 // the first type of QDBusMessage is delivered.
781 // The D-Bus specification requires that all MethodCall messages be replied to, unless the
782 // caller specifically waived this requirement. This means that we inspect if the user slot
783 // generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
784 // QDBusMessage parameter, it cannot generate a reply.
786 // When a return message is generated, the slot's return type, if any, will be placed
787 // in the message's first position. If there are non-const reference parameters to the
788 // slot, they must appear at the end and will be placed in the subsequent message
791 static const char cachePropertyName[] = "_qdbus_slotCache";
796 #ifndef QT_NO_PROPERTIES
797 Q_ASSERT_X(QThread::currentThread() == object->thread(),
798 "QDBusConnection: internal threading error",
799 "function called for an object that is in another thread!!");
801 QDBusSlotCache slotCache =
802 qvariant_cast<QDBusSlotCache>(object->property(cachePropertyName));
803 QString cacheKey = msg.member(), signature = msg.signature();
804 if (!signature.isEmpty()) {
805 cacheKey.reserve(cacheKey.length() + 1 + signature.length());
806 cacheKey += QLatin1Char('.');
807 cacheKey += signature;
810 QDBusSlotCache::Hash::ConstIterator cacheIt = slotCache.hash.constFind(cacheKey);
811 while (cacheIt != slotCache.hash.constEnd() && cacheIt->flags != flags &&
812 cacheIt.key() == cacheKey)
814 if (cacheIt == slotCache.hash.constEnd() || cacheIt.key() != cacheKey)
816 // not cached, analyze the meta object
817 const QMetaObject *mo = object->metaObject();
818 QByteArray memberName = msg.member().toUtf8();
820 // find a slot that matches according to the rules above
821 QDBusSlotCache::Data slotData;
822 slotData.flags = flags;
823 slotData.slotIdx = ::findSlot(mo, memberName, flags, msg.signature(), slotData.metaTypes);
824 if (slotData.slotIdx == -1) {
825 // ### this is where we want to add the connection as an arg too
826 // try with no parameters, but with a QDBusMessage
827 slotData.slotIdx = ::findSlot(mo, memberName, flags, QString(), slotData.metaTypes);
828 if (slotData.metaTypes.count() != 2 ||
829 slotData.metaTypes.at(1) != QDBusMetaTypeId::message) {
831 // save the negative lookup
832 slotData.slotIdx = -1;
833 slotData.metaTypes.clear();
834 slotCache.hash.insert(cacheKey, slotData);
835 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
841 slotCache.hash.insert(cacheKey, slotData);
842 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
844 // found the slot to be called
845 deliverCall(object, flags, msg, slotData.metaTypes, slotData.slotIdx);
847 } else if (cacheIt->slotIdx == -1) {
852 deliverCall(object, flags, msg, cacheIt->metaTypes, cacheIt->slotIdx);
855 #endif // QT_NO_PROPERTIES
859 void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const QDBusMessage &msg,
860 const QList<int> &metaTypes, int slotIdx)
862 Q_ASSERT_X(!object || QThread::currentThread() == object->thread(),
863 "QDBusConnection: internal threading error",
864 "function called for an object that is in another thread!!");
866 QVarLengthArray<void *, 10> params;
867 params.reserve(metaTypes.count());
869 QVariantList auxParameters;
870 // let's create the parameter list
872 // first one is the return type -- add it below
875 // add the input parameters
877 int pCount = qMin(msg.arguments().count(), metaTypes.count() - 1);
878 for (i = 1; i <= pCount; ++i) {
879 int id = metaTypes[i];
880 if (id == QDBusMetaTypeId::message)
883 const QVariant &arg = msg.arguments().at(i - 1);
884 if (arg.userType() == id)
885 // no conversion needed
886 params.append(const_cast<void *>(arg.constData()));
887 else if (arg.userType() == qMetaTypeId<QDBusArgument>()) {
888 // convert to what the function expects
890 auxParameters.append(QVariant(id, null));
892 const QDBusArgument &in =
893 *reinterpret_cast<const QDBusArgument *>(arg.constData());
894 QVariant &out = auxParameters[auxParameters.count() - 1];
896 if (!QDBusMetaType::demarshall(in, out.userType(), out.data()))
897 qFatal("Internal error: demarshalling function for type '%s' (%d) failed!",
898 out.typeName(), out.userType());
900 params.append(const_cast<void *>(out.constData()));
902 qFatal("Internal error: got invalid meta type %d (%s) "
903 "when trying to convert to meta type %d (%s)",
904 arg.userType(), QMetaType::typeName(arg.userType()),
905 id, QMetaType::typeName(id));
909 bool takesMessage = false;
910 if (metaTypes.count() > i && metaTypes[i] == QDBusMetaTypeId::message) {
911 params.append(const_cast<void*>(static_cast<const void*>(&msg)));
917 QVariantList outputArgs;
919 if (metaTypes[0] != QMetaType::Void) {
920 QVariant arg(metaTypes[0], null);
921 outputArgs.append( arg );
922 params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
924 for ( ; i < metaTypes.count(); ++i) {
925 QVariant arg(metaTypes[i], null);
926 outputArgs.append( arg );
927 params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
935 // FIXME: save the old sender!
936 QDBusContextPrivate context(QDBusConnection(this), msg);
937 QDBusContextPrivate *old = QDBusContextPrivate::set(object, &context);
938 QDBusConnectionPrivate::setSender(this);
940 QPointer<QObject> ptr = object;
941 fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
942 slotIdx, params.data()) >= 0;
943 QDBusConnectionPrivate::setSender(0);
944 // the object might be deleted in the slot
946 QDBusContextPrivate::set(object, old);
949 // do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
951 if (msg.isReplyRequired() && !msg.isDelayedReply()) {
954 qDBusDebug() << this << "Automatically sending reply:" << outputArgs;
955 send(msg.createReply(outputArgs));
957 // generate internal error
958 qWarning("Internal error: Failed to deliver message");
959 send(msg.createErrorReply(QDBusError::InternalError,
960 QLatin1String("Failed to deliver message")));
967 extern bool qDBusInitThreads();
969 QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
970 : QObject(p), ref(1), capabilities(0), mode(InvalidMode), connection(0), server(0), busService(0),
971 watchAndTimeoutLock(QMutex::Recursive),
972 rootNode(QString(QLatin1Char('/')))
974 static const bool threads = q_dbus_threads_init_default();
975 static const int debugging = qgetenv("QDBUS_DEBUG").toInt();
976 ::isDebugging = debugging;
980 #ifdef QDBUS_THREAD_DEBUG
982 qdbusThreadDebug = qdbusDefaultThreadDebug;
985 QDBusMetaTypeId::init();
989 // prepopulate watchedServices:
990 // we know that the owner of org.freedesktop.DBus is itself
991 watchedServices.insert(dbusServiceString(), WatchedServiceData(dbusServiceString(), 1));
993 // prepopulate matchRefCounts:
994 // we know that org.freedesktop.DBus will never change owners
995 matchRefCounts.insert("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.DBus'", 1);
998 QDBusConnectionPrivate::~QDBusConnectionPrivate()
1000 if (thread() && thread() != QThread::currentThread())
1001 qWarning("QDBusConnection(name=\"%s\")'s last reference in not in its creation thread! "
1002 "Timer and socket errors will follow and the program will probably crash",
1006 rootNode.children.clear(); // free resources
1007 qDeleteAll(cachedMetaObjects);
1010 q_dbus_server_unref(server);
1012 q_dbus_connection_unref(connection);
1018 void QDBusConnectionPrivate::deleteYourself()
1020 if (thread() && thread() != QThread::currentThread()) {
1021 // last reference dropped while not in the correct thread
1022 // ask the correct thread to delete
1024 // note: since we're posting an event to another thread, we
1025 // must consider deleteLater() to take effect immediately
1032 void QDBusConnectionPrivate::closeConnection()
1034 QDBusWriteLocker locker(CloseConnectionAction, this);
1035 ConnectionMode oldMode = mode;
1036 mode = InvalidMode; // prevent reentrancy
1037 baseService.clear();
1040 q_dbus_server_disconnect(server);
1042 if (oldMode == ClientMode || oldMode == PeerMode) {
1044 q_dbus_connection_close(connection);
1045 // send the "close" message
1046 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS)
1052 void QDBusConnectionPrivate::checkThread()
1055 if (QCoreApplication::instance())
1056 moveToThread(QCoreApplication::instance()->thread());
1058 qWarning("The thread that had QDBusConnection('%s') has died and there is no main thread",
1063 bool QDBusConnectionPrivate::handleError(const QDBusErrorInternal &error)
1066 return false; // no error
1068 //lock.lockForWrite();
1074 void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
1077 QDBusWatchAndTimeoutLocker locker(TimerEventAction, this);
1078 DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
1080 q_dbus_timeout_handle(timeout);
1086 void QDBusConnectionPrivate::customEvent(QEvent *e)
1088 Q_ASSERT(e->type() == QEvent::User);
1090 QDBusConnectionCallbackEvent *ev = static_cast<QDBusConnectionCallbackEvent *>(e);
1091 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1092 QDBusLockerBase::BeforeDeliver, this);
1093 switch (ev->subtype)
1095 case QDBusConnectionCallbackEvent::AddTimeout: {
1096 QDBusWatchAndTimeoutLocker locker(RealAddTimeoutAction, this);
1097 while (!timeoutsPendingAdd.isEmpty()) {
1098 QPair<DBusTimeout *, int> entry = timeoutsPendingAdd.takeFirst();
1099 qDBusRealAddTimeout(this, entry.first, entry.second);
1104 case QDBusConnectionCallbackEvent::KillTimer:
1105 killTimer(ev->timerId);
1108 case QDBusConnectionCallbackEvent::AddWatch:
1109 qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
1112 case QDBusConnectionCallbackEvent::ToggleWatch:
1113 qDBusRealToggleWatch(this, ev->watch, ev->fd);
1116 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1117 QDBusLockerBase::AfterDeliver, this);
1120 void QDBusConnectionPrivate::doDispatch()
1122 QDBusDispatchLocker locker(DoDispatchAction, this);
1123 if (mode == ClientMode || mode == PeerMode)
1124 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
1127 void QDBusConnectionPrivate::socketRead(int fd)
1129 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1132 QDBusWatchAndTimeoutLocker locker(SocketReadAction, this);
1133 WatcherHash::ConstIterator it = watchers.constFind(fd);
1134 while (it != watchers.constEnd() && it.key() == fd) {
1135 if (it->watch && it->read && it->read->isEnabled())
1136 pendingWatches.append(it.value().watch);
1141 for (int i = 0; i < pendingWatches.size(); ++i)
1142 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_READABLE))
1143 qDebug("OUT OF MEM");
1147 void QDBusConnectionPrivate::socketWrite(int fd)
1149 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1152 QDBusWatchAndTimeoutLocker locker(SocketWriteAction, this);
1153 WatcherHash::ConstIterator it = watchers.constFind(fd);
1154 while (it != watchers.constEnd() && it.key() == fd) {
1155 if (it->watch && it->write && it->write->isEnabled())
1156 pendingWatches.append(it.value().watch);
1161 for (int i = 0; i < pendingWatches.size(); ++i)
1162 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_WRITABLE))
1163 qDebug("OUT OF MEM");
1166 void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
1168 QDBusWriteLocker locker(ObjectDestroyedAction, this);
1169 huntAndDestroy(obj, rootNode);
1171 SignalHookHash::iterator sit = signalHooks.begin();
1172 while (sit != signalHooks.end()) {
1173 if (static_cast<QObject *>(sit.value().obj) == obj)
1174 sit = disconnectSignal(sit);
1179 obj->disconnect(this);
1182 void QDBusConnectionPrivate::relaySignal(QObject *obj, const QMetaObject *mo, int signalId,
1183 const QVariantList &args)
1185 QString interface = qDBusInterfaceFromMetaObject(mo);
1187 QMetaMethod mm = mo->method(signalId);
1188 QByteArray memberName = mm.signature();
1189 memberName.truncate(memberName.indexOf('('));
1191 // check if it's scriptable
1192 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
1193 bool isAdaptor = false;
1194 for ( ; mo; mo = mo->superClass())
1195 if (mo == &QDBusAbstractAdaptor::staticMetaObject) {
1200 QDBusReadLocker locker(RelaySignalAction, this);
1201 QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/"), interface,
1202 QLatin1String(memberName));
1203 QDBusMessagePrivate::setParametersValidated(message, true);
1204 message.setArguments(args);
1206 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1208 qWarning("QDBusConnection: Could not emit signal %s.%s: %s", qPrintable(interface), memberName.constData(),
1209 qPrintable(error.message()));
1214 //qDBusDebug() << "Emitting signal" << message;
1215 //qDBusDebug() << "for paths:";
1216 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1217 huntAndEmit(connection, msg, obj, rootNode, isScriptable, isAdaptor);
1218 q_dbus_message_unref(msg);
1221 void QDBusConnectionPrivate::serviceOwnerChangedNoLock(const QString &name,
1222 const QString &oldOwner, const QString &newOwner)
1225 // QDBusWriteLocker locker(UpdateSignalHookOwnerAction, this);
1226 WatchedServicesHash::Iterator it = watchedServices.find(name);
1227 if (it == watchedServices.end())
1229 if (oldOwner != it->owner)
1230 qWarning("QDBusConnection: name '%s' had owner '%s' but we thought it was '%s'",
1231 qPrintable(name), qPrintable(oldOwner), qPrintable(it->owner));
1233 qDBusDebug() << this << "Updating name" << name << "from" << oldOwner << "to" << newOwner;
1234 it->owner = newOwner;
1237 int QDBusConnectionPrivate::findSlot(QObject* obj, const QByteArray &normalizedName,
1240 int midx = obj->metaObject()->indexOfMethod(normalizedName);
1244 int inputCount = qDBusParametersForMethod(obj->metaObject()->method(midx), params);
1245 if ( inputCount == -1 || inputCount + 1 != params.count() )
1246 return -1; // failed to parse or invalid arguments or output arguments
1251 bool QDBusConnectionPrivate::prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
1252 const QString &service,
1253 const QString &path, const QString &interface, const QString &name,
1254 const QStringList &argMatch,
1255 QObject *receiver, const char *signal, int minMIdx,
1256 bool buildSignature)
1258 QByteArray normalizedName = signal + 1;
1259 hook.midx = findSlot(receiver, signal + 1, hook.params);
1260 if (hook.midx == -1) {
1261 normalizedName = QMetaObject::normalizedSignature(signal + 1);
1262 hook.midx = findSlot(receiver, normalizedName, hook.params);
1264 if (hook.midx < minMIdx) {
1265 if (hook.midx == -1)
1270 hook.service = service;
1272 hook.obj = receiver;
1273 hook.argumentMatch = argMatch;
1275 // build the D-Bus signal name and signature
1276 // This should not happen for QDBusConnection::connect, use buildSignature here, since
1277 // QDBusConnection::connect passes false and everything else uses true
1278 QString mname = name;
1279 if (buildSignature && mname.isNull()) {
1280 normalizedName.truncate(normalizedName.indexOf('('));
1281 mname = QString::fromUtf8(normalizedName);
1284 key.reserve(interface.length() + 1 + mname.length());
1285 key += QLatin1Char(':');
1288 if (buildSignature) {
1289 hook.signature.clear();
1290 for (int i = 1; i < hook.params.count(); ++i)
1291 if (hook.params.at(i) != QDBusMetaTypeId::message)
1292 hook.signature += QLatin1String( QDBusMetaType::typeToSignature( hook.params.at(i) ) );
1295 hook.matchRule = buildMatchRule(service, path, interface, mname, argMatch, hook.signature);
1296 return true; // connect to this signal
1299 void QDBusConnectionPrivate::sendError(const QDBusMessage &msg, QDBusError::ErrorType code)
1301 if (code == QDBusError::UnknownMethod) {
1302 QString interfaceMsg;
1303 if (msg.interface().isEmpty())
1304 interfaceMsg = QLatin1String("any interface");
1306 interfaceMsg = QString::fromLatin1("interface '%1'").arg(msg.interface());
1308 send(msg.createErrorReply(code,
1309 QString::fromLatin1("No such method '%1' in %2 at object path '%3' "
1311 .arg(msg.member(), interfaceMsg, msg.path(), msg.signature())));
1312 } else if (code == QDBusError::UnknownInterface) {
1313 send(msg.createErrorReply(QDBusError::UnknownInterface,
1314 QString::fromLatin1("No such interface '%1' at object path '%2'")
1315 .arg(msg.interface(), msg.path())));
1316 } else if (code == QDBusError::UnknownObject) {
1317 send(msg.createErrorReply(QDBusError::UnknownObject,
1318 QString::fromLatin1("No such object path '%1'").arg(msg.path())));
1322 bool QDBusConnectionPrivate::activateInternalFilters(const ObjectTreeNode &node,
1323 const QDBusMessage &msg)
1325 // object may be null
1326 const QString interface = msg.interface();
1328 if (interface.isEmpty() || interface == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE)) {
1329 if (msg.member() == QLatin1String("Introspect") && msg.signature().isEmpty()) {
1330 //qDebug() << "QDBusConnectionPrivate::activateInternalFilters introspect" << msg.d_ptr->msg;
1331 QDBusMessage reply = msg.createReply(qDBusIntrospectObject(node));
1336 if (!interface.isEmpty()) {
1337 sendError(msg, QDBusError::UnknownMethod);
1342 if (node.obj && (interface.isEmpty() ||
1343 interface == QLatin1String(DBUS_INTERFACE_PROPERTIES))) {
1344 //qDebug() << "QDBusConnectionPrivate::activateInternalFilters properties" << msg.d_ptr->msg;
1345 if (msg.member() == QLatin1String("Get") && msg.signature() == QLatin1String("ss")) {
1346 QDBusMessage reply = qDBusPropertyGet(node, msg);
1349 } else if (msg.member() == QLatin1String("Set") && msg.signature() == QLatin1String("ssv")) {
1350 QDBusMessage reply = qDBusPropertySet(node, msg);
1353 } else if (msg.member() == QLatin1String("GetAll") && msg.signature() == QLatin1String("s")) {
1354 QDBusMessage reply = qDBusPropertyGetAll(node, msg);
1359 if (!interface.isEmpty()) {
1360 sendError(msg, QDBusError::UnknownMethod);
1368 void QDBusConnectionPrivate::activateObject(ObjectTreeNode &node, const QDBusMessage &msg,
1371 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call to a slot
1374 // The call is routed through the adaptor sub-objects if we have any
1376 // object may be null
1378 if (pathStartPos != msg.path().length()) {
1379 node.flags &= ~QDBusConnection::ExportAllSignals;
1380 node.obj = findChildObject(&node, msg.path(), pathStartPos);
1382 sendError(msg, QDBusError::UnknownObject);
1387 QDBusAdaptorConnector *connector;
1388 if (node.flags & QDBusConnection::ExportAdaptors &&
1389 (connector = qDBusFindAdaptorConnector(node.obj))) {
1390 int newflags = node.flags | QDBusConnection::ExportAllSlots;
1392 if (msg.interface().isEmpty()) {
1393 // place the call in all interfaces
1394 // let the first one that handles it to work
1395 QDBusAdaptorConnector::AdaptorMap::ConstIterator it =
1396 connector->adaptors.constBegin();
1397 QDBusAdaptorConnector::AdaptorMap::ConstIterator end =
1398 connector->adaptors.constEnd();
1400 for ( ; it != end; ++it)
1401 if (activateCall(it->adaptor, newflags, msg))
1404 // check if we have an interface matching the name that was asked:
1405 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
1406 it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
1408 if (it != connector->adaptors.constEnd() && msg.interface() == QLatin1String(it->interface)) {
1409 if (!activateCall(it->adaptor, newflags, msg))
1410 sendError(msg, QDBusError::UnknownMethod);
1416 // no adaptors matched or were exported
1417 // try our standard filters
1418 if (activateInternalFilters(node, msg))
1419 return; // internal filters have already run or an error has been sent
1421 // try the object itself:
1422 if (node.flags & (QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportNonScriptableSlots) ||
1423 node.flags & (QDBusConnection::ExportScriptableInvokables|QDBusConnection::ExportNonScriptableInvokables)) {
1424 bool interfaceFound = true;
1425 if (!msg.interface().isEmpty())
1426 interfaceFound = qDBusInterfaceInObject(node.obj, msg.interface());
1428 if (interfaceFound) {
1429 if (!activateCall(node.obj, node.flags, msg))
1430 sendError(msg, QDBusError::UnknownMethod);
1435 // nothing matched, send an error code
1436 if (msg.interface().isEmpty())
1437 sendError(msg, QDBusError::UnknownMethod);
1439 sendError(msg, QDBusError::UnknownInterface);
1442 void QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
1444 // if the msg is external, we were called from inside doDispatch
1445 // that means the dispatchLock mutex is locked
1446 // must not call out to user code in that case
1448 // however, if the message is internal, handleMessage was called
1449 // directly and no lock is in place. We can therefore call out to
1450 // user code, if necessary
1451 ObjectTreeNode result;
1453 QThread *objThread = 0;
1458 QDBusReadLocker locker(HandleObjectCallAction, this);
1459 if (!findObject(&rootNode, msg.path(), usedLength, result)) {
1460 // qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
1461 sendError(msg, QDBusError::UnknownObject);
1466 // no object -> no threading issues
1467 // it's either going to be an error, or an internal filter
1468 activateObject(result, msg, usedLength);
1472 objThread = result.obj->thread();
1474 send(msg.createErrorReply(QDBusError::InternalError,
1475 QString::fromLatin1("Object '%1' (at path '%2')"
1476 " has no thread. Cannot deliver message.")
1477 .arg(result.obj->objectName(), msg.path())));
1481 if (!QDBusMessagePrivate::isLocal(msg)) {
1482 // external incoming message
1483 // post it and forget
1484 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1485 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1488 } else if (objThread != QThread::currentThread()) {
1489 // synchronize with other thread
1490 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1491 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1492 usedLength, msg, &sem));
1497 } // release the lock
1500 SEM_ACQUIRE(HandleObjectCallSemaphoreAction, sem);
1502 activateObject(result, msg, usedLength);
1505 QDBusActivateObjectEvent::~QDBusActivateObjectEvent()
1508 // we're being destroyed without delivering
1509 // it means the object was deleted between posting and delivering
1510 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1511 that->sendError(message, QDBusError::UnknownObject);
1514 // semaphore releasing happens in ~QMetaCallEvent
1517 void QDBusActivateObjectEvent::placeMetaCall(QObject *)
1519 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1521 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1522 QDBusLockerBase::BeforeDeliver, that);
1523 that->activateObject(node, message, pathStartPos);
1524 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1525 QDBusLockerBase::AfterDeliver, that);
1530 void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1532 SignalHookHash::const_iterator it = signalHooks.find(key);
1533 SignalHookHash::const_iterator end = signalHooks.constEnd();
1534 //qDebug("looking for: %s", path.toLocal8Bit().constData());
1535 //qDBusDebug() << signalHooks.keys();
1536 for ( ; it != end && it.key() == key; ++it) {
1537 const SignalHook &hook = it.value();
1538 if (!hook.service.isEmpty()) {
1539 const QString owner =
1540 shouldWatchService(hook.service) ?
1541 watchedServices.value(hook.service).owner :
1543 if (owner != msg.service())
1546 if (!hook.path.isEmpty() && hook.path != msg.path())
1548 if (!hook.signature.isEmpty() && hook.signature != msg.signature())
1550 if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1552 if (!hook.argumentMatch.isEmpty()) {
1553 const QVariantList arguments = msg.arguments();
1554 if (hook.argumentMatch.size() > arguments.size())
1557 bool matched = true;
1558 for (int i = 0; i < hook.argumentMatch.size(); ++i) {
1559 const QString ¶m = hook.argumentMatch.at(i);
1561 continue; // don't try to match against this
1562 if (param == arguments.at(i).toString())
1563 continue; // matched
1571 activateSignal(hook, msg);
1575 void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1577 // We call handlesignal(QString, QDBusMessage) three times:
1578 // one with member:interface
1580 // one with :interface
1581 // This allows us to match signals with wildcards on member or interface
1584 QString key = msg.member();
1585 key.reserve(key.length() + 1 + msg.interface().length());
1586 key += QLatin1Char(':');
1587 key += msg.interface();
1589 QDBusReadLocker locker(HandleSignalAction, this);
1590 handleSignal(key, msg); // one try
1592 key.truncate(msg.member().length() + 1); // keep the ':'
1593 handleSignal(key, msg); // second try
1595 key = QLatin1Char(':');
1596 key += msg.interface();
1597 handleSignal(key, msg); // third try
1600 static dbus_int32_t server_slot = -1;
1602 void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
1612 dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
1613 if (data_allocated && server_slot < 0)
1616 dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
1621 //qDebug() << "watch_functions_set" << watch_functions_set;
1622 Q_UNUSED(watch_functions_set);
1624 dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
1629 //qDebug() << "time_functions_set" << time_functions_set;
1630 Q_UNUSED(time_functions_set);
1632 q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1634 dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
1635 //qDebug() << "data_set" << data_set;
1639 void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
1649 q_dbus_connection_set_exit_on_disconnect(connection, false);
1650 q_dbus_connection_set_watch_functions(connection,
1655 q_dbus_connection_set_timeout_functions(connection,
1660 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1661 q_dbus_connection_add_filter(connection,
1665 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1668 static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnection *connection)
1670 QDBusConnection::ConnectionCapabilities result = 0;
1672 #if defined(QT_LINKED_LIBDBUS) && DBUS_VERSION < 0x010400
1673 // no capabilities are possible
1675 # if !defined(QT_LINKED_LIBDBUS)
1676 // run-time check if the next functions are available
1677 int major, minor, micro;
1678 q_dbus_get_version(&major, &minor, µ);
1679 if (major == 1 && minor < 4)
1683 #ifndef DBUS_TYPE_UNIX_FD
1684 # define DBUS_TYPE_UNIX_FD int('h')
1686 if (q_dbus_connection_can_send_type(connection, DBUS_TYPE_UNIX_FD))
1687 result |= QDBusConnection::UnixFileDescriptorPassing;
1693 void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
1703 const char *service = q_dbus_bus_get_unique_name(connection);
1705 baseService = QString::fromUtf8(service);
1706 capabilities = connectionCapabilies(connection);
1708 q_dbus_connection_set_exit_on_disconnect(connection, false);
1709 q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1710 qDBusToggleWatch, this, 0);
1711 q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1712 qDBusToggleTimeout, this, 0);
1713 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1714 q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1716 // Initialize the hooks for the NameAcquired and NameLost signals
1717 // we don't use connectSignal here because we don't need the rules to be sent to the bus
1718 // the bus will always send us these two signals
1720 hook.service = dbusServiceString();
1721 hook.path.clear(); // no matching
1723 hook.params << QMetaType::Void << QVariant::String; // both functions take a QString as parameter and return void
1725 hook.midx = staticMetaObject.indexOfSlot("registerServiceNoLock(QString)");
1726 Q_ASSERT(hook.midx != -1);
1727 signalHooks.insert(QLatin1String("NameAcquired:" DBUS_INTERFACE_DBUS), hook);
1729 hook.midx = staticMetaObject.indexOfSlot("unregisterServiceNoLock(QString)");
1730 Q_ASSERT(hook.midx != -1);
1731 signalHooks.insert(QLatin1String("NameLost:" DBUS_INTERFACE_DBUS), hook);
1733 qDBusDebug() << this << ": connected successfully";
1735 // schedule a dispatch:
1736 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1740 static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1742 QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
1743 Q_ASSERT(call->pending == pending);
1745 QDBusConnectionPrivate::processFinishedCall(call);
1749 void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
1751 Q_ASSERT(pcall->pending);
1752 Q_ASSERT(!pcall->autoDelete);
1753 //Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
1755 if (pcall->waitingForFinished) {
1756 // another thread is already waiting
1757 pcall->waitForFinishedCondition.wait(&pcall->mutex);
1759 pcall->waitingForFinished = true;
1760 pcall->mutex.unlock();
1763 QDBusDispatchLocker locker(PendingCallBlockAction, this);
1764 q_dbus_pending_call_block(pcall->pending);
1765 // QDBusConnectionPrivate::processFinishedCall() is called automatically
1767 pcall->mutex.lock();
1771 void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
1773 QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1775 QMutexLocker locker(&call->mutex);
1777 QDBusMessage &msg = call->replyMessage;
1778 if (call->pending) {
1779 // decode the message
1780 DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
1781 msg = QDBusMessagePrivate::fromDBusMessage(reply, connection->capabilities);
1782 q_dbus_message_unref(reply);
1784 qDBusDebug() << connection << "got message reply (async):" << msg;
1786 // Check if the reply has the expected signature
1787 call->checkReceivedSignature();
1789 if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
1790 // Deliver the return values of a remote function call.
1792 // There is only one connection and it is specified by idx
1793 // The slot must have the same parameter types that the message does
1794 // The slot may have less parameters than the message
1795 // The slot may optionally have one final parameter that is QDBusMessage
1796 // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1798 QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
1799 call->metaTypes, msg);
1801 connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
1803 qDBusDebug() << "Deliver failed!";
1807 q_dbus_pending_call_unref(call->pending);
1812 // Are there any watchers?
1813 if (call->watcherHelper)
1814 call->watcherHelper->emitSignals(msg, call->sentMessage);
1816 if (msg.type() == QDBusMessage::ErrorMessage)
1817 emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
1819 if (call->autoDelete) {
1820 Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
1825 int QDBusConnectionPrivate::send(const QDBusMessage& message)
1827 if (QDBusMessagePrivate::isLocal(message))
1828 return -1; // don't send; the reply will be retrieved by the caller
1829 // through the d_ptr->localReply link
1832 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1834 if (message.type() == QDBusMessage::MethodCallMessage)
1835 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1836 qPrintable(message.service()), qPrintable(message.path()),
1837 qPrintable(message.interface()), qPrintable(message.member()),
1838 qPrintable(error.message()));
1839 else if (message.type() == QDBusMessage::SignalMessage)
1840 qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
1841 qPrintable(message.path()), qPrintable(message.interface()),
1842 qPrintable(message.member()),
1843 qPrintable(error.message()));
1845 qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
1846 message.type() == QDBusMessage::ReplyMessage ? "reply" :
1847 message.type() == QDBusMessage::ErrorMessage ? "error" :
1848 "invalid", qPrintable(message.service()),
1849 qPrintable(error.message()));
1854 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1856 qDBusDebug() << this << "sending message (no reply):" << message;
1858 bool isOk = q_dbus_connection_send(connection, msg, 0);
1861 serial = q_dbus_message_get_serial(msg);
1863 q_dbus_message_unref(msg);
1867 QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1868 int sendMode, int timeout)
1871 if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
1872 && isServiceRegisteredByThread(message.service()))
1873 // special case for synchronous local calls
1874 return sendWithReplyLocal(message);
1876 if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
1878 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &err);
1880 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1881 qPrintable(message.service()), qPrintable(message.path()),
1882 qPrintable(message.interface()), qPrintable(message.member()),
1883 qPrintable(err.message()));
1885 return QDBusMessage::createError(err);
1888 qDBusDebug() << this << "sending message (blocking):" << message;
1889 QDBusErrorInternal error;
1890 DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
1892 q_dbus_message_unref(msg);
1895 lastError = err = error;
1896 return QDBusMessage::createError(err);
1899 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply, capabilities);
1900 q_dbus_message_unref(reply);
1901 qDBusDebug() << this << "got message reply (blocking):" << amsg;
1904 } else { // use the event loop
1905 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1908 if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
1909 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
1911 loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
1912 loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
1914 // enter the event loop and wait for a reply
1915 loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1918 QDBusMessage reply = pcall->replyMessage;
1919 lastError = reply; // set or clear error
1926 QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
1928 qDBusDebug() << this << "sending message via local-loop:" << message;
1930 QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
1931 bool handled = handleMessage(localCallMsg);
1934 QString interface = message.interface();
1935 if (interface.isEmpty())
1936 interface = QLatin1String("<no-interface>");
1937 return QDBusMessage::createError(QDBusError::InternalError,
1938 QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
1939 .arg(interface, message.member(),
1940 message.path(), message.signature()));
1943 // if the message was handled, there might be a reply
1944 QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
1945 if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
1946 qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
1947 "on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
1948 qPrintable(message.signature()));
1949 return QDBusMessage::createError(
1950 QDBusError(QDBusError::InternalError,
1951 QLatin1String("local-loop message cannot have delayed replies")));
1955 qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
1956 return localReplyMsg;
1959 QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
1962 if (isServiceRegisteredByThread(message.service())) {
1963 // special case for local calls
1964 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1965 pcall->replyMessage = sendWithReplyLocal(message);
1971 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1975 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1977 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1978 qPrintable(message.service()), qPrintable(message.path()),
1979 qPrintable(message.interface()), qPrintable(message.member()),
1980 qPrintable(error.message()));
1981 pcall->replyMessage = QDBusMessage::createError(error);
1986 qDBusDebug() << this << "sending message (async):" << message;
1987 DBusPendingCall *pending = 0;
1989 QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
1990 if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
1992 q_dbus_message_unref(msg);
1994 pcall->pending = pending;
1995 q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
1999 // we're probably disconnected at this point
2000 lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
2003 lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
2006 q_dbus_message_unref(msg);
2007 pcall->replyMessage = QDBusMessage::createError(error);
2011 int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
2012 const char *returnMethod, const char *errorMethod,
2015 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
2018 // has it already finished with success (dispatched locally)?
2019 if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
2020 pcall->setReplyCallback(receiver, returnMethod);
2021 processFinishedCall(pcall);
2026 // either it hasn't finished or it has finished with error
2028 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
2029 connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
2030 Qt::QueuedConnection);
2031 pcall->watcherHelper->moveToThread(thread());
2034 // has it already finished and is an error reply message?
2035 if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
2036 processFinishedCall(pcall);
2041 pcall->autoDelete = true;
2043 pcall->setReplyCallback(receiver, returnMethod);
2048 bool QDBusConnectionPrivate::connectSignal(const QString &service,
2049 const QString &path, const QString &interface, const QString &name,
2050 const QStringList &argumentMatch, const QString &signature,
2051 QObject *receiver, const char *slot)
2054 QDBusConnectionPrivate::SignalHook hook;
2056 QString name2 = name;
2060 hook.signature = signature;
2061 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2062 return false; // don't connect
2064 // avoid duplicating:
2065 QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.find(key);
2066 QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
2067 for ( ; it != end && it.key() == key; ++it) {
2068 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2069 if (entry.service == hook.service &&
2070 entry.path == hook.path &&
2071 entry.signature == hook.signature &&
2072 entry.obj == hook.obj &&
2073 entry.midx == hook.midx &&
2074 entry.argumentMatch == hook.argumentMatch) {
2075 // no need to compare the parameters if it's the same slot
2076 return true; // already there
2080 connectSignal(key, hook);
2084 void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
2086 signalHooks.insertMulti(key, hook);
2087 connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2088 Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
2090 MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
2092 if (it != matchRefCounts.end()) { // Match already present
2093 it.value() = it.value() + 1;
2097 matchRefCounts.insert(hook.matchRule, 1);
2100 if (mode != QDBusConnectionPrivate::PeerMode) {
2101 qDBusDebug("Adding rule: %s", hook.matchRule.constData());
2102 q_dbus_bus_add_match(connection, hook.matchRule, NULL);
2104 // Successfully connected the signal
2105 // Do we need to watch for this name?
2106 if (shouldWatchService(hook.service)) {
2107 WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
2108 if (++data.refcount == 1) {
2109 // we need to watch for this service changing
2110 connectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2111 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2112 this, SLOT(serviceOwnerChangedNoLock(QString,QString,QString)));
2113 data.owner = getNameOwnerNoCache(hook.service);
2114 qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
2115 << data.owner << ")";
2122 bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
2123 const QString &path, const QString &interface, const QString &name,
2124 const QStringList &argumentMatch, const QString &signature,
2125 QObject *receiver, const char *slot)
2128 QDBusConnectionPrivate::SignalHook hook;
2130 QString name2 = name;
2134 hook.signature = signature;
2135 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2136 return false; // don't disconnect
2138 // avoid duplicating:
2139 QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
2140 QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
2141 for ( ; it != end && it.key() == key; ++it) {
2142 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2143 if (entry.service == hook.service &&
2144 entry.path == hook.path &&
2145 entry.signature == hook.signature &&
2146 entry.obj == hook.obj &&
2147 entry.midx == hook.midx &&
2148 entry.argumentMatch == hook.argumentMatch) {
2149 // no need to compare the parameters if it's the same slot
2150 disconnectSignal(it);
2151 return true; // it was there
2155 // the slot was not found
2159 QDBusConnectionPrivate::SignalHookHash::Iterator
2160 QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
2162 const SignalHook &hook = it.value();
2165 MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
2166 if (i == matchRefCounts.end()) {
2167 qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
2169 if (i.value() == 1) {
2171 matchRefCounts.erase(i);
2174 i.value() = i.value() - 1;
2178 // we don't care about errors here
2179 if (connection && erase) {
2180 if (mode != QDBusConnectionPrivate::PeerMode) {
2181 qDBusDebug("Removing rule: %s", hook.matchRule.constData());
2182 q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
2184 // Successfully disconnected the signal
2185 // Were we watching for this name?
2186 WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
2187 if (sit != watchedServices.end()) {
2188 if (--sit.value().refcount == 0) {
2189 watchedServices.erase(sit);
2190 disconnectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2191 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2192 this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
2199 return signalHooks.erase(it);
2202 void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
2204 connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2205 Qt::DirectConnection);
2207 if (node->flags & (QDBusConnection::ExportAdaptors
2208 | QDBusConnection::ExportScriptableSignals
2209 | QDBusConnection::ExportNonScriptableSignals)) {
2210 QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
2212 if (node->flags & (QDBusConnection::ExportScriptableSignals
2213 | QDBusConnection::ExportNonScriptableSignals)) {
2214 connector->disconnectAllSignals(node->obj);
2215 connector->connectAllSignals(node->obj);
2218 // disconnect and reconnect to avoid duplicates
2219 connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2220 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
2221 connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2222 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2223 Qt::DirectConnection);
2227 void QDBusConnectionPrivate::connectRelay(const QString &service,
2228 const QString &path, const QString &interface,
2229 QDBusAbstractInterface *receiver,
2232 // this function is called by QDBusAbstractInterface when one of its signals is connected
2233 // we set up a relay from D-Bus into it
2237 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
2238 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2239 return; // don't connect
2241 // add it to our list:
2242 QDBusWriteLocker locker(ConnectRelayAction, this);
2243 SignalHookHash::ConstIterator it = signalHooks.find(key);
2244 SignalHookHash::ConstIterator end = signalHooks.constEnd();
2245 for ( ; it != end && it.key() == key; ++it) {
2246 const SignalHook &entry = it.value();
2247 if (entry.service == hook.service &&
2248 entry.path == hook.path &&
2249 entry.signature == hook.signature &&
2250 entry.obj == hook.obj &&
2251 entry.midx == hook.midx)
2252 return; // already there, no need to re-add
2255 connectSignal(key, hook);
2258 void QDBusConnectionPrivate::disconnectRelay(const QString &service,
2259 const QString &path, const QString &interface,
2260 QDBusAbstractInterface *receiver,
2263 // this function is called by QDBusAbstractInterface when one of its signals is disconnected
2264 // we remove relay from D-Bus into it
2268 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
2269 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2270 return; // don't connect
2272 // remove it from our list:
2273 QDBusWriteLocker locker(DisconnectRelayAction, this);
2274 SignalHookHash::Iterator it = signalHooks.find(key);
2275 SignalHookHash::Iterator end = signalHooks.end();
2276 for ( ; it != end && it.key() == key; ++it) {
2277 const SignalHook &entry = it.value();
2278 if (entry.service == hook.service &&
2279 entry.path == hook.path &&
2280 entry.signature == hook.signature &&
2281 entry.obj == hook.obj &&
2282 entry.midx == hook.midx) {
2284 disconnectSignal(it);
2289 qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
2292 QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
2294 if (QDBusUtil::isValidUniqueConnectionName(serviceName))
2300 // acquire a read lock for the cache
2301 QReadLocker locker(&lock);
2302 WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
2303 if (it != watchedServices.constEnd())
2308 return getNameOwnerNoCache(serviceName);
2311 QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
2313 QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2314 QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2315 QLatin1String("GetNameOwner"));
2316 QDBusMessagePrivate::setParametersValidated(msg, true);
2318 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2319 if (reply.type() == QDBusMessage::ReplyMessage)
2320 return reply.arguments().at(0).toString();
2325 QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
2326 const QString &interface, QDBusError &error)
2328 // service must be a unique connection name
2329 if (!interface.isEmpty()) {
2330 QDBusReadLocker locker(FindMetaObject1Action, this);
2331 QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
2336 // introspect the target object
2337 QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
2338 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
2339 QLatin1String("Introspect"));
2340 QDBusMessagePrivate::setParametersValidated(msg, true);
2342 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2344 // it doesn't exist yet, we have to create it
2345 QDBusWriteLocker locker(FindMetaObject2Action, this);
2346 QDBusMetaObject *mo = 0;
2347 if (!interface.isEmpty())
2348 mo = cachedMetaObjects.value(interface, 0);
2350 // maybe it got created when we switched from read to write lock
2354 if (reply.type() == QDBusMessage::ReplyMessage) {
2355 if (reply.signature() == QLatin1String("s"))
2356 // fetch the XML description
2357 xml = reply.arguments().at(0).toString();
2361 if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
2365 // release the lock and return
2366 QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
2367 cachedMetaObjects, error);
2372 void QDBusConnectionPrivate::registerService(const QString &serviceName)
2374 QDBusWriteLocker locker(RegisterServiceAction, this);
2375 registerServiceNoLock(serviceName);
2378 void QDBusConnectionPrivate::registerServiceNoLock(const QString &serviceName)
2380 serviceNames.append(serviceName);
2383 void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
2385 QDBusWriteLocker locker(UnregisterServiceAction, this);
2386 unregisterServiceNoLock(serviceName);
2389 void QDBusConnectionPrivate::unregisterServiceNoLock(const QString &serviceName)
2391 serviceNames.removeAll(serviceName);
2394 bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
2396 if (!serviceName.isEmpty() && serviceName == baseService)
2398 QStringList copy = serviceNames;
2399 return copy.contains(serviceName);
2402 void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
2404 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
2405 QCoreApplication::postEvent(object, ev);
2406 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
2411 #endif // QT_NO_DBUS