1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtDBus module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
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 "qdbusvirtualobject.h"
61 #include "qdbusmessage_p.h"
62 #include "qdbuscontext_p.h"
63 #include "qdbuspendingcall_p.h"
64 #include "qdbusintegrator_p.h"
66 #include "qdbusthreaddebug_p.h"
72 static bool isDebugging;
73 #define qDBusDebug if (!::isDebugging); else qDebug
75 Q_GLOBAL_STATIC_WITH_ARGS(const QString, orgFreedesktopDBusString, (QLatin1String(DBUS_SERVICE_DBUS)))
77 static inline QString dbusServiceString()
78 { return *orgFreedesktopDBusString(); }
79 static inline QString dbusInterfaceString()
81 // it's the same string, but just be sure
82 Q_ASSERT(*orgFreedesktopDBusString() == QLatin1String(DBUS_INTERFACE_DBUS));
83 return *orgFreedesktopDBusString();
86 static inline QDebug operator<<(QDebug dbg, const QThread *th)
88 dbg.nospace() << "QThread(ptr=" << (void*)th;
89 if (th && !th->objectName().isEmpty())
90 dbg.nospace() << ", name=" << th->objectName();
95 #if QDBUS_THREAD_DEBUG
96 static inline QDebug operator<<(QDebug dbg, const QDBusConnectionPrivate *conn)
98 dbg.nospace() << "QDBusConnection("
99 << "ptr=" << (void*)conn
100 << ", name=" << conn->name
101 << ", baseService=" << conn->baseService
103 if (conn->thread() == QThread::currentThread())
104 dbg.nospace() << "same thread";
106 dbg.nospace() << conn->thread();
107 dbg.nospace() << ')';
111 Q_AUTOTEST_EXPORT void qdbusDefaultThreadDebug(int action, int condition, QDBusConnectionPrivate *conn)
113 qDBusDebug() << QThread::currentThread()
114 << "QtDBus threading action" << action
115 << (condition == QDBusLockerBase::BeforeLock ? "before lock" :
116 condition == QDBusLockerBase::AfterLock ? "after lock" :
117 condition == QDBusLockerBase::BeforeUnlock ? "before unlock" :
118 condition == QDBusLockerBase::AfterUnlock ? "after unlock" :
119 condition == QDBusLockerBase::BeforePost ? "before event posting" :
120 condition == QDBusLockerBase::AfterPost ? "after event posting" :
121 condition == QDBusLockerBase::BeforeDeliver ? "before event delivery" :
122 condition == QDBusLockerBase::AfterDeliver ? "after event delivery" :
123 condition == QDBusLockerBase::BeforeAcquire ? "before acquire" :
124 condition == QDBusLockerBase::AfterAcquire ? "after acquire" :
125 condition == QDBusLockerBase::BeforeRelease ? "before release" :
126 condition == QDBusLockerBase::AfterRelease ? "after release" :
128 << "in connection" << conn;
130 Q_AUTOTEST_EXPORT qdbusThreadDebugFunc qdbusThreadDebug = 0;
133 typedef void (*QDBusSpyHook)(const QDBusMessage&);
134 typedef QVarLengthArray<QDBusSpyHook, 4> QDBusSpyHookList;
135 Q_GLOBAL_STATIC(QDBusSpyHookList, qDBusSpyHookList)
139 // libdbus-1 callbacks
141 static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms);
142 static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
147 // qDebug("addTimeout %d", q_dbus_timeout_get_interval(timeout));
149 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
151 if (!q_dbus_timeout_get_enabled(timeout))
154 QDBusWatchAndTimeoutLocker locker(AddTimeoutAction, d);
155 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
157 return qDBusRealAddTimeout(d, timeout, q_dbus_timeout_get_interval(timeout));
159 // wrong thread: sync back
160 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
161 ev->subtype = QDBusConnectionCallbackEvent::AddTimeout;
162 d->timeoutsPendingAdd.append(qMakePair(timeout, q_dbus_timeout_get_interval(timeout)));
163 d->postEventToThread(AddTimeoutAction, d, ev);
168 static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms)
170 Q_ASSERT(d->timeouts.keys(timeout).isEmpty());
172 int timerId = d->startTimer(ms);
176 d->timeouts[timerId] = timeout;
180 static void qDBusRemoveTimeout(DBusTimeout *timeout, void *data)
185 // qDebug("removeTimeout");
187 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
189 QDBusWatchAndTimeoutLocker locker(RemoveTimeoutAction, d);
191 // is it pending addition?
192 QDBusConnectionPrivate::PendingTimeoutList::iterator pit = d->timeoutsPendingAdd.begin();
193 while (pit != d->timeoutsPendingAdd.end()) {
194 if (pit->first == timeout)
195 pit = d->timeoutsPendingAdd.erase(pit);
200 // is it a running timer?
201 bool correctThread = QCoreApplication::instance() && QThread::currentThread() == d->thread();
202 QDBusConnectionPrivate::TimeoutHash::iterator it = d->timeouts.begin();
203 while (it != d->timeouts.end()) {
204 if (it.value() == timeout) {
207 d->killTimer(it.key());
209 // incorrect thread or no application, post an event for later
210 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
211 ev->subtype = QDBusConnectionCallbackEvent::KillTimer;
212 ev->timerId = it.key();
213 d->postEventToThread(KillTimerAction, d, ev);
215 it = d->timeouts.erase(it);
223 static void qDBusToggleTimeout(DBusTimeout *timeout, void *data)
228 //qDebug("ToggleTimeout");
230 qDBusRemoveTimeout(timeout, data);
231 qDBusAddTimeout(timeout, data);
234 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd);
235 static dbus_bool_t qDBusAddWatch(DBusWatch *watch, void *data)
240 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
242 int flags = q_dbus_watch_get_flags(watch);
243 int fd = q_dbus_watch_get_fd(watch);
245 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
246 return qDBusRealAddWatch(d, watch, flags, fd);
248 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
249 ev->subtype = QDBusConnectionCallbackEvent::AddWatch;
253 d->postEventToThread(AddWatchAction, d, ev);
258 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd)
260 QDBusConnectionPrivate::Watcher watcher;
262 QDBusWatchAndTimeoutLocker locker(AddWatchAction, d);
263 if (flags & DBUS_WATCH_READABLE) {
264 //qDebug("addReadWatch %d", fd);
265 watcher.watch = watch;
266 if (QCoreApplication::instance()) {
267 watcher.read = new QSocketNotifier(fd, QSocketNotifier::Read, d);
268 watcher.read->setEnabled(q_dbus_watch_get_enabled(watch));
269 d->connect(watcher.read, SIGNAL(activated(int)), SLOT(socketRead(int)));
272 if (flags & DBUS_WATCH_WRITABLE) {
273 //qDebug("addWriteWatch %d", fd);
274 watcher.watch = watch;
275 if (QCoreApplication::instance()) {
276 watcher.write = new QSocketNotifier(fd, QSocketNotifier::Write, d);
277 watcher.write->setEnabled(q_dbus_watch_get_enabled(watch));
278 d->connect(watcher.write, SIGNAL(activated(int)), SLOT(socketWrite(int)));
281 d->watchers.insertMulti(fd, watcher);
286 static void qDBusRemoveWatch(DBusWatch *watch, void *data)
291 //qDebug("remove watch");
293 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
294 int fd = q_dbus_watch_get_fd(watch);
296 QDBusWatchAndTimeoutLocker locker(RemoveWatchAction, d);
297 QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
298 while (i != d->watchers.end() && i.key() == fd) {
299 if (i.value().watch == watch) {
300 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
301 // correct thread, delete the socket notifiers
302 delete i.value().read;
303 delete i.value().write;
305 // incorrect thread or no application, use delete later
307 i->read->deleteLater();
309 i->write->deleteLater();
311 i = d->watchers.erase(i);
318 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd);
319 static void qDBusToggleWatch(DBusWatch *watch, void *data)
324 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
325 int fd = q_dbus_watch_get_fd(watch);
327 if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
328 qDBusRealToggleWatch(d, watch, fd);
330 QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
331 ev->subtype = QDBusConnectionCallbackEvent::ToggleWatch;
334 d->postEventToThread(ToggleWatchAction, d, ev);
338 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd)
340 QDBusWatchAndTimeoutLocker locker(ToggleWatchAction, d);
342 QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
343 while (i != d->watchers.end() && i.key() == fd) {
344 if (i.value().watch == watch) {
345 bool enabled = q_dbus_watch_get_enabled(watch);
346 int flags = q_dbus_watch_get_flags(watch);
348 //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);
350 if (flags & DBUS_WATCH_READABLE && i.value().read)
351 i.value().read->setEnabled(enabled);
352 if (flags & DBUS_WATCH_WRITABLE && i.value().write)
353 i.value().write->setEnabled(enabled);
360 static void qDBusUpdateDispatchStatus(DBusConnection *connection, DBusDispatchStatus new_status, void *data)
362 Q_ASSERT(connection);
363 Q_UNUSED(connection);
364 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
366 static int slotId; // 0 is QObject::deleteLater()
368 // it's ok to do this: there's no race condition because the store is atomic
369 // and we always set to the same value
370 slotId = QDBusConnectionPrivate::staticMetaObject.indexOfSlot("doDispatch()");
373 //qDBusDebug() << "Updating dispatcher status" << slotId;
374 if (new_status == DBUS_DISPATCH_DATA_REMAINS)
375 QDBusConnectionPrivate::staticMetaObject.method(slotId).
376 invoke(d, Qt::QueuedConnection);
379 static void qDBusNewConnection(DBusServer *server, DBusConnection *connection, void *data)
381 // ### We may want to separate the server from the QDBusConnectionPrivate
382 Q_ASSERT(server); Q_UNUSED(server);
383 Q_ASSERT(connection);
386 // keep the connection alive
387 q_dbus_connection_ref(connection);
388 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
390 // setPeer does the error handling for us
391 QDBusErrorInternal error;
392 d->setPeer(connection, error);
394 QDBusConnection retval = QDBusConnectionPrivate::q(d);
396 // make QDBusServer emit the newConnection signal
397 d->serverConnection(retval);
402 static QByteArray buildMatchRule(const QString &service,
403 const QString &objectPath, const QString &interface,
404 const QString &member, const QStringList &argMatch, const QString & /*signature*/)
406 QString result = QLatin1String("type='signal',");
407 QString keyValue = QLatin1String("%1='%2',");
409 if (!service.isEmpty())
410 result += keyValue.arg(QLatin1String("sender"), service);
411 if (!objectPath.isEmpty())
412 result += keyValue.arg(QLatin1String("path"), objectPath);
413 if (!interface.isEmpty())
414 result += keyValue.arg(QLatin1String("interface"), interface);
415 if (!member.isEmpty())
416 result += keyValue.arg(QLatin1String("member"), member);
418 // add the argument string-matching now
419 if (!argMatch.isEmpty()) {
420 keyValue = QLatin1String("arg%1='%2',");
421 for (int i = 0; i < argMatch.count(); ++i)
422 if (!argMatch.at(i).isNull())
423 result += keyValue.arg(i).arg(argMatch.at(i));
426 result.chop(1); // remove ending comma
427 return result.toLatin1();
430 static bool findObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
431 const QString &fullpath, int &usedLength,
432 QDBusConnectionPrivate::ObjectTreeNode &result)
434 if (!fullpath.compare(QLatin1String("/")) && root->obj) {
440 int length = fullpath.length();
441 if (fullpath.at(0) == QLatin1Char('/'))
444 // walk the object tree
445 const QDBusConnectionPrivate::ObjectTreeNode *node = root;
446 while (start < length && node) {
447 if (node->flags & QDBusConnection::ExportChildObjects)
449 if ((node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath))
451 int end = fullpath.indexOf(QLatin1Char('/'), start);
452 end = (end == -1 ? length : end);
453 QStringRef pathComponent(&fullpath, start, end - start);
455 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
456 qLowerBound(node->children.constBegin(), node->children.constEnd(), pathComponent);
457 if (it != node->children.constEnd() && it->name == pathComponent)
467 usedLength = (start > length ? length : start);
469 if (node->obj || !node->children.isEmpty())
472 // there really is no object here
473 // we're just looking at an unused space in the QVector
479 static QObject *findChildObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
480 const QString &fullpath, int start)
482 int length = fullpath.length();
484 // any object in the tree can tell us to switch to its own object tree:
485 const QDBusConnectionPrivate::ObjectTreeNode *node = root;
486 if (node && node->flags & QDBusConnection::ExportChildObjects) {
487 QObject *obj = node->obj;
491 // we're at the correct level
494 int pos = fullpath.indexOf(QLatin1Char('/'), start);
495 pos = (pos == -1 ? length : pos);
496 QStringRef pathComponent(&fullpath, start, pos - start);
498 const QObjectList children = obj->children();
500 // find a child with the proper name
502 QObjectList::ConstIterator it = children.constBegin();
503 QObjectList::ConstIterator end = children.constEnd();
504 for ( ; it != end; ++it)
505 if ((*it)->objectName() == pathComponent) {
522 static bool shouldWatchService(const QString &service)
524 return !service.isEmpty() && !service.startsWith(QLatin1Char(':'));
527 extern Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook);
528 void qDBusAddSpyHook(QDBusSpyHook hook)
530 qDBusSpyHookList()->append(hook);
534 static DBusHandlerResult
535 qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
538 Q_UNUSED(connection);
539 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
540 if (d->mode == QDBusConnectionPrivate::InvalidMode)
541 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
543 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(message, d->capabilities);
544 qDBusDebug() << d << "got message (signal):" << amsg;
546 return d->handleMessage(amsg) ?
547 DBUS_HANDLER_RESULT_HANDLED :
548 DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
552 bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
554 const QDBusSpyHookList *list = qDBusSpyHookList();
555 for (int i = 0; i < list->size(); ++i) {
556 qDBusDebug() << "calling the message spy hook";
563 switch (amsg.type()) {
564 case QDBusMessage::SignalMessage:
566 // if there are any other filters in this DBusConnection,
567 // let them see the signal too
569 case QDBusMessage::MethodCallMessage:
570 handleObjectCall(amsg);
572 case QDBusMessage::ReplyMessage:
573 case QDBusMessage::ErrorMessage:
574 case QDBusMessage::InvalidMessage:
575 return false; // we don't handle those here
581 static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode &haystack)
583 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it = haystack.children.begin();
584 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator end = haystack.children.end();
585 for ( ; it != end; ++it)
586 huntAndDestroy(needle, *it);
588 if (needle == haystack.obj) {
594 static void huntAndEmit(DBusConnection *connection, DBusMessage *msg,
595 QObject *needle, const QDBusConnectionPrivate::ObjectTreeNode &haystack,
596 bool isScriptable, bool isAdaptor, const QString &path = QString())
598 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it = haystack.children.constBegin();
599 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end = haystack.children.constEnd();
600 for ( ; it != end; ++it)
601 huntAndEmit(connection, msg, needle, *it, isScriptable, isAdaptor, path + QLatin1Char('/') + it->name);
603 if (needle == haystack.obj) {
604 // is this a signal we should relay?
605 if (isAdaptor && (haystack.flags & QDBusConnection::ExportAdaptors) == 0)
606 return; // no: it comes from an adaptor and we're not exporting adaptors
607 else if (!isAdaptor) {
608 int mask = isScriptable
609 ? QDBusConnection::ExportScriptableSignals
610 : QDBusConnection::ExportNonScriptableSignals;
611 if ((haystack.flags & mask) == 0)
612 return; // signal was not exported
615 QByteArray p = path.toLatin1();
618 qDBusDebug() << QThread::currentThread() << "emitting signal at" << p;
619 DBusMessage *msg2 = q_dbus_message_copy(msg);
620 q_dbus_message_set_path(msg2, p);
621 q_dbus_connection_send(connection, msg2, 0);
622 q_dbus_message_unref(msg2);
626 static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
627 const QString &signature_, QVector<int> &metaTypes)
629 QByteArray msgSignature = signature_.toLatin1();
631 for (int idx = mo->methodCount() - 1 ; idx >= QObject::staticMetaObject.methodCount(); --idx) {
632 QMetaMethod mm = mo->method(idx);
635 if (mm.access() != QMetaMethod::Public)
639 if (mm.methodType() != QMetaMethod::Slot && mm.methodType() != QMetaMethod::Method)
643 if (mm.name() != name)
646 int returnType = mm.returnType();
647 bool isAsync = qDBusCheckAsyncTag(mm.tag());
648 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
650 // consistency check:
651 if (isAsync && returnType != QMetaType::Void)
654 int inputCount = qDBusParametersForMethod(mm, metaTypes);
655 if (inputCount == -1)
656 continue; // problem parsing
658 metaTypes[0] = returnType;
659 bool hasMessage = false;
660 if (inputCount > 0 &&
661 metaTypes.at(inputCount) == QDBusMetaTypeId::message) {
662 // "no input parameters" is allowed as long as the message meta type is there
667 // try to match the parameters
669 QByteArray reconstructedSignature;
670 for (i = 1; i <= inputCount; ++i) {
671 const char *typeSignature = QDBusMetaType::typeToSignature( metaTypes.at(i) );
675 reconstructedSignature += typeSignature;
676 if (!msgSignature.startsWith(reconstructedSignature))
680 if (reconstructedSignature != msgSignature)
681 continue; // we didn't match them all
686 // make sure that the output parameters have signatures too
687 if (returnType != QMetaType::UnknownType && returnType != QMetaType::Void && QDBusMetaType::typeToSignature(returnType) == 0)
691 for (int j = i; ok && j < metaTypes.count(); ++j)
692 if (QDBusMetaType::typeToSignature(metaTypes.at(i)) == 0)
697 // consistency check:
698 if (isAsync && metaTypes.count() > i + 1)
701 if (mm.methodType() == QMetaMethod::Slot) {
702 if (isScriptable && (flags & QDBusConnection::ExportScriptableSlots) == 0)
703 continue; // scriptable slots not exported
704 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableSlots) == 0)
705 continue; // non-scriptable slots not exported
707 if (isScriptable && (flags & QDBusConnection::ExportScriptableInvokables) == 0)
708 continue; // scriptable invokables not exported
709 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableInvokables) == 0)
710 continue; // non-scriptable invokables not exported
713 // if we got here, this slot matched
721 static QDBusCallDeliveryEvent * const DIRECT_DELIVERY = (QDBusCallDeliveryEvent *)1;
723 QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
724 QObject *object, int idx,
725 const QVector<int> &metaTypes,
726 const QDBusMessage &msg)
731 int n = metaTypes.count() - 1;
732 if (metaTypes[n] == QDBusMetaTypeId::message)
735 if (msg.arguments().count() < n)
736 return 0; // too few arguments
738 // check that types match
739 for (int i = 0; i < n; ++i)
740 if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() &&
741 msg.arguments().at(i).userType() != qMetaTypeId<QDBusArgument>())
742 return 0; // no match
745 // prepare for the call
746 if (target == object)
747 return DIRECT_DELIVERY;
748 return new QDBusCallDeliveryEvent(QDBusConnection(target), idx, target, msg, metaTypes);
751 void QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
752 const QDBusMessage &msg)
754 // This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
755 // that was received from D-Bus
757 // Signals are delivered to slots if the parameters match
758 // Slots can have less parameters than there are on the message
759 // Slots can optionally have one final parameter that is a QDBusMessage
760 // Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
761 QDBusCallDeliveryEvent *call = prepareReply(this, hook.obj, hook.midx, hook.params, msg);
762 if (call == DIRECT_DELIVERY) {
763 // short-circuit delivery
764 Q_ASSERT(this == hook.obj);
765 deliverCall(this, 0, msg, hook.params, hook.midx);
769 postEventToThread(ActivateSignalAction, hook.obj, call);
772 bool QDBusConnectionPrivate::activateCall(QObject* object, int flags, const QDBusMessage &msg)
774 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call
775 // to a slot on the object.
777 // The call is delivered to the first slot that matches the following conditions:
778 // - has the same name as the message's target member
779 // - ALL of the message's types are found in slot's parameter list
780 // - optionally has one more parameter of type QDBusMessage
781 // If none match, then the slot of the same name as the message target and with
782 // the first type of QDBusMessage is delivered.
784 // The D-Bus specification requires that all MethodCall messages be replied to, unless the
785 // caller specifically waived this requirement. This means that we inspect if the user slot
786 // generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
787 // QDBusMessage parameter, it cannot generate a reply.
789 // When a return message is generated, the slot's return type, if any, will be placed
790 // in the message's first position. If there are non-const reference parameters to the
791 // slot, they must appear at the end and will be placed in the subsequent message
794 static const char cachePropertyName[] = "_qdbus_slotCache";
799 #ifndef QT_NO_PROPERTIES
800 Q_ASSERT_X(QThread::currentThread() == object->thread(),
801 "QDBusConnection: internal threading error",
802 "function called for an object that is in another thread!!");
804 QDBusSlotCache slotCache =
805 qvariant_cast<QDBusSlotCache>(object->property(cachePropertyName));
806 QString cacheKey = msg.member(), signature = msg.signature();
807 if (!signature.isEmpty()) {
808 cacheKey.reserve(cacheKey.length() + 1 + signature.length());
809 cacheKey += QLatin1Char('.');
810 cacheKey += signature;
813 QDBusSlotCache::Hash::ConstIterator cacheIt = slotCache.hash.constFind(cacheKey);
814 while (cacheIt != slotCache.hash.constEnd() && cacheIt->flags != flags &&
815 cacheIt.key() == cacheKey)
817 if (cacheIt == slotCache.hash.constEnd() || cacheIt.key() != cacheKey)
819 // not cached, analyze the meta object
820 const QMetaObject *mo = object->metaObject();
821 QByteArray memberName = msg.member().toUtf8();
823 // find a slot that matches according to the rules above
824 QDBusSlotCache::Data slotData;
825 slotData.flags = flags;
826 slotData.slotIdx = ::findSlot(mo, memberName, flags, msg.signature(), slotData.metaTypes);
827 if (slotData.slotIdx == -1) {
828 // ### this is where we want to add the connection as an arg too
829 // try with no parameters, but with a QDBusMessage
830 slotData.slotIdx = ::findSlot(mo, memberName, flags, QString(), slotData.metaTypes);
831 if (slotData.metaTypes.count() != 2 ||
832 slotData.metaTypes.at(1) != QDBusMetaTypeId::message) {
834 // save the negative lookup
835 slotData.slotIdx = -1;
836 slotData.metaTypes.clear();
837 slotCache.hash.insert(cacheKey, slotData);
838 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
844 slotCache.hash.insert(cacheKey, slotData);
845 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
847 // found the slot to be called
848 deliverCall(object, flags, msg, slotData.metaTypes, slotData.slotIdx);
850 } else if (cacheIt->slotIdx == -1) {
855 deliverCall(object, flags, msg, cacheIt->metaTypes, cacheIt->slotIdx);
858 #endif // QT_NO_PROPERTIES
862 void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const QDBusMessage &msg,
863 const QVector<int> &metaTypes, int slotIdx)
865 Q_ASSERT_X(!object || QThread::currentThread() == object->thread(),
866 "QDBusConnection: internal threading error",
867 "function called for an object that is in another thread!!");
869 QVarLengthArray<void *, 10> params;
870 params.reserve(metaTypes.count());
872 QVariantList auxParameters;
873 // let's create the parameter list
875 // first one is the return type -- add it below
878 // add the input parameters
880 int pCount = qMin(msg.arguments().count(), metaTypes.count() - 1);
881 for (i = 1; i <= pCount; ++i) {
882 int id = metaTypes[i];
883 if (id == QDBusMetaTypeId::message)
886 const QVariant &arg = msg.arguments().at(i - 1);
887 if (arg.userType() == id)
888 // no conversion needed
889 params.append(const_cast<void *>(arg.constData()));
890 else if (arg.userType() == qMetaTypeId<QDBusArgument>()) {
891 // convert to what the function expects
893 auxParameters.append(QVariant(id, null));
895 const QDBusArgument &in =
896 *reinterpret_cast<const QDBusArgument *>(arg.constData());
897 QVariant &out = auxParameters[auxParameters.count() - 1];
899 if (!QDBusMetaType::demarshall(in, out.userType(), out.data()))
900 qFatal("Internal error: demarshalling function for type '%s' (%d) failed!",
901 out.typeName(), out.userType());
903 params.append(const_cast<void *>(out.constData()));
905 qFatal("Internal error: got invalid meta type %d (%s) "
906 "when trying to convert to meta type %d (%s)",
907 arg.userType(), QMetaType::typeName(arg.userType()),
908 id, QMetaType::typeName(id));
912 if (metaTypes.count() > i && metaTypes[i] == QDBusMetaTypeId::message) {
913 params.append(const_cast<void*>(static_cast<const void*>(&msg)));
918 QVariantList outputArgs;
920 if (metaTypes[0] != QMetaType::Void && metaTypes[0] != QMetaType::UnknownType) {
921 QVariant arg(metaTypes[0], null);
922 outputArgs.append( arg );
923 params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
925 for ( ; i < metaTypes.count(); ++i) {
926 QVariant arg(metaTypes[i], null);
927 outputArgs.append( arg );
928 params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
936 // FIXME: save the old sender!
937 QDBusContextPrivate context(QDBusConnection(this), msg);
938 QDBusContextPrivate *old = QDBusContextPrivate::set(object, &context);
939 QDBusConnectionPrivate::setSender(this);
941 QPointer<QObject> ptr = object;
942 fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
943 slotIdx, params.data()) >= 0;
944 QDBusConnectionPrivate::setSender(0);
945 // the object might be deleted in the slot
947 QDBusContextPrivate::set(object, old);
950 // do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
952 if (msg.isReplyRequired() && !msg.isDelayedReply()) {
955 qDBusDebug() << this << "Automatically sending reply:" << outputArgs;
956 send(msg.createReply(outputArgs));
958 // generate internal error
959 qWarning("Internal error: Failed to deliver message");
960 send(msg.createErrorReply(QDBusError::InternalError,
961 QLatin1String("Failed to deliver message")));
968 extern bool qDBusInitThreads();
970 QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
971 : QObject(p), ref(1), capabilities(0), mode(InvalidMode), connection(0), server(0), busService(0),
972 watchAndTimeoutLock(QMutex::Recursive),
973 rootNode(QString(QLatin1Char('/')))
975 static const bool threads = q_dbus_threads_init_default();
976 static const int debugging = qgetenv("QDBUS_DEBUG").toInt();
977 ::isDebugging = debugging;
981 #ifdef QDBUS_THREAD_DEBUG
983 qdbusThreadDebug = qdbusDefaultThreadDebug;
986 QDBusMetaTypeId::init();
990 // prepopulate watchedServices:
991 // we know that the owner of org.freedesktop.DBus is itself
992 watchedServices.insert(dbusServiceString(), WatchedServiceData(dbusServiceString(), 1));
994 // prepopulate matchRefCounts:
995 // we know that org.freedesktop.DBus will never change owners
996 matchRefCounts.insert("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.DBus'", 1);
999 QDBusConnectionPrivate::~QDBusConnectionPrivate()
1001 if (thread() && thread() != QThread::currentThread())
1002 qWarning("QDBusConnection(name=\"%s\")'s last reference in not in its creation thread! "
1003 "Timer and socket errors will follow and the program will probably crash",
1007 rootNode.children.clear(); // free resources
1008 qDeleteAll(cachedMetaObjects);
1011 q_dbus_server_unref(server);
1013 q_dbus_connection_unref(connection);
1019 void QDBusConnectionPrivate::deleteYourself()
1021 if (thread() && thread() != QThread::currentThread()) {
1022 // last reference dropped while not in the correct thread
1023 // ask the correct thread to delete
1025 // note: since we're posting an event to another thread, we
1026 // must consider deleteLater() to take effect immediately
1033 void QDBusConnectionPrivate::closeConnection()
1035 QDBusWriteLocker locker(CloseConnectionAction, this);
1036 ConnectionMode oldMode = mode;
1037 mode = InvalidMode; // prevent reentrancy
1038 baseService.clear();
1041 q_dbus_server_disconnect(server);
1043 if (oldMode == ClientMode || oldMode == PeerMode) {
1045 q_dbus_connection_close(connection);
1046 // send the "close" message
1047 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS)
1053 void QDBusConnectionPrivate::checkThread()
1056 if (QCoreApplication::instance())
1057 moveToThread(QCoreApplication::instance()->thread());
1059 qWarning("The thread that had QDBusConnection('%s') has died and there is no main thread",
1064 bool QDBusConnectionPrivate::handleError(const QDBusErrorInternal &error)
1067 return false; // no error
1069 //lock.lockForWrite();
1075 void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
1078 QDBusWatchAndTimeoutLocker locker(TimerEventAction, this);
1079 DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
1081 q_dbus_timeout_handle(timeout);
1087 void QDBusConnectionPrivate::customEvent(QEvent *e)
1089 Q_ASSERT(e->type() == QEvent::User);
1091 QDBusConnectionCallbackEvent *ev = static_cast<QDBusConnectionCallbackEvent *>(e);
1092 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1093 QDBusLockerBase::BeforeDeliver, this);
1094 switch (ev->subtype)
1096 case QDBusConnectionCallbackEvent::AddTimeout: {
1097 QDBusWatchAndTimeoutLocker locker(RealAddTimeoutAction, this);
1098 while (!timeoutsPendingAdd.isEmpty()) {
1099 QPair<DBusTimeout *, int> entry = timeoutsPendingAdd.takeFirst();
1100 qDBusRealAddTimeout(this, entry.first, entry.second);
1105 case QDBusConnectionCallbackEvent::KillTimer:
1106 killTimer(ev->timerId);
1109 case QDBusConnectionCallbackEvent::AddWatch:
1110 qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
1113 case QDBusConnectionCallbackEvent::ToggleWatch:
1114 qDBusRealToggleWatch(this, ev->watch, ev->fd);
1117 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1118 QDBusLockerBase::AfterDeliver, this);
1121 void QDBusConnectionPrivate::doDispatch()
1123 QDBusDispatchLocker locker(DoDispatchAction, this);
1124 if (mode == ClientMode || mode == PeerMode)
1125 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
1128 void QDBusConnectionPrivate::socketRead(int fd)
1130 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1133 QDBusWatchAndTimeoutLocker locker(SocketReadAction, this);
1134 WatcherHash::ConstIterator it = watchers.constFind(fd);
1135 while (it != watchers.constEnd() && it.key() == fd) {
1136 if (it->watch && it->read && it->read->isEnabled())
1137 pendingWatches.append(it.value().watch);
1142 for (int i = 0; i < pendingWatches.size(); ++i)
1143 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_READABLE))
1144 qDebug("OUT OF MEM");
1148 void QDBusConnectionPrivate::socketWrite(int fd)
1150 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1153 QDBusWatchAndTimeoutLocker locker(SocketWriteAction, this);
1154 WatcherHash::ConstIterator it = watchers.constFind(fd);
1155 while (it != watchers.constEnd() && it.key() == fd) {
1156 if (it->watch && it->write && it->write->isEnabled())
1157 pendingWatches.append(it.value().watch);
1162 for (int i = 0; i < pendingWatches.size(); ++i)
1163 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_WRITABLE))
1164 qDebug("OUT OF MEM");
1167 void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
1169 QDBusWriteLocker locker(ObjectDestroyedAction, this);
1170 huntAndDestroy(obj, rootNode);
1172 SignalHookHash::iterator sit = signalHooks.begin();
1173 while (sit != signalHooks.end()) {
1174 if (static_cast<QObject *>(sit.value().obj) == obj)
1175 sit = disconnectSignal(sit);
1180 obj->disconnect(this);
1183 void QDBusConnectionPrivate::relaySignal(QObject *obj, const QMetaObject *mo, int signalId,
1184 const QVariantList &args)
1186 QString interface = qDBusInterfaceFromMetaObject(mo);
1188 QMetaMethod mm = mo->method(signalId);
1189 QByteArray memberName = mm.name();
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,
1238 QVector<int> ¶ms)
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, msg.path()));
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 (node.flags & QDBusConnectionPrivate::VirtualObject) {
1379 if (node.treeNode->handleMessage(msg, q(this))) {
1382 if (activateInternalFilters(node, msg))
1387 if (pathStartPos != msg.path().length()) {
1388 node.flags &= ~QDBusConnection::ExportAllSignals;
1389 node.obj = findChildObject(&node, msg.path(), pathStartPos);
1391 sendError(msg, QDBusError::UnknownObject);
1396 QDBusAdaptorConnector *connector;
1397 if (node.flags & QDBusConnection::ExportAdaptors &&
1398 (connector = qDBusFindAdaptorConnector(node.obj))) {
1399 int newflags = node.flags | QDBusConnection::ExportAllSlots;
1401 if (msg.interface().isEmpty()) {
1402 // place the call in all interfaces
1403 // let the first one that handles it to work
1404 QDBusAdaptorConnector::AdaptorMap::ConstIterator it =
1405 connector->adaptors.constBegin();
1406 QDBusAdaptorConnector::AdaptorMap::ConstIterator end =
1407 connector->adaptors.constEnd();
1409 for ( ; it != end; ++it)
1410 if (activateCall(it->adaptor, newflags, msg))
1413 // check if we have an interface matching the name that was asked:
1414 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
1415 it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
1417 if (it != connector->adaptors.constEnd() && msg.interface() == QLatin1String(it->interface)) {
1418 if (!activateCall(it->adaptor, newflags, msg))
1419 sendError(msg, QDBusError::UnknownMethod);
1425 // no adaptors matched or were exported
1426 // try our standard filters
1427 if (activateInternalFilters(node, msg))
1428 return; // internal filters have already run or an error has been sent
1430 // try the object itself:
1431 if (node.flags & (QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportNonScriptableSlots) ||
1432 node.flags & (QDBusConnection::ExportScriptableInvokables|QDBusConnection::ExportNonScriptableInvokables)) {
1433 bool interfaceFound = true;
1434 if (!msg.interface().isEmpty())
1435 interfaceFound = qDBusInterfaceInObject(node.obj, msg.interface());
1437 if (interfaceFound) {
1438 if (!activateCall(node.obj, node.flags, msg))
1439 sendError(msg, QDBusError::UnknownMethod);
1444 // nothing matched, send an error code
1445 if (msg.interface().isEmpty())
1446 sendError(msg, QDBusError::UnknownMethod);
1448 sendError(msg, QDBusError::UnknownInterface);
1451 void QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
1453 // if the msg is external, we were called from inside doDispatch
1454 // that means the dispatchLock mutex is locked
1455 // must not call out to user code in that case
1457 // however, if the message is internal, handleMessage was called
1458 // directly and no lock is in place. We can therefore call out to
1459 // user code, if necessary
1460 ObjectTreeNode result;
1462 QThread *objThread = 0;
1467 QDBusReadLocker locker(HandleObjectCallAction, this);
1468 if (!findObject(&rootNode, msg.path(), usedLength, result)) {
1469 // qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
1470 sendError(msg, QDBusError::UnknownObject);
1475 // no object -> no threading issues
1476 // it's either going to be an error, or an internal filter
1477 activateObject(result, msg, usedLength);
1481 objThread = result.obj->thread();
1483 send(msg.createErrorReply(QDBusError::InternalError,
1484 QString::fromLatin1("Object '%1' (at path '%2')"
1485 " has no thread. Cannot deliver message.")
1486 .arg(result.obj->objectName(), msg.path())));
1490 if (!QDBusMessagePrivate::isLocal(msg)) {
1491 // external incoming message
1492 // post it and forget
1493 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1494 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1497 } else if (objThread != QThread::currentThread()) {
1498 // synchronize with other thread
1499 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1500 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1501 usedLength, msg, &sem));
1506 } // release the lock
1509 SEM_ACQUIRE(HandleObjectCallSemaphoreAction, sem);
1511 activateObject(result, msg, usedLength);
1514 QDBusActivateObjectEvent::~QDBusActivateObjectEvent()
1517 // we're being destroyed without delivering
1518 // it means the object was deleted between posting and delivering
1519 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1520 that->sendError(message, QDBusError::UnknownObject);
1523 // semaphore releasing happens in ~QMetaCallEvent
1526 void QDBusActivateObjectEvent::placeMetaCall(QObject *)
1528 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1530 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1531 QDBusLockerBase::BeforeDeliver, that);
1532 that->activateObject(node, message, pathStartPos);
1533 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1534 QDBusLockerBase::AfterDeliver, that);
1539 void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1541 SignalHookHash::const_iterator it = signalHooks.find(key);
1542 SignalHookHash::const_iterator end = signalHooks.constEnd();
1543 //qDebug("looking for: %s", path.toLocal8Bit().constData());
1544 //qDBusDebug() << signalHooks.keys();
1545 for ( ; it != end && it.key() == key; ++it) {
1546 const SignalHook &hook = it.value();
1547 if (!hook.service.isEmpty()) {
1548 const QString owner =
1549 shouldWatchService(hook.service) ?
1550 watchedServices.value(hook.service).owner :
1552 if (owner != msg.service())
1555 if (!hook.path.isEmpty() && hook.path != msg.path())
1557 if (!hook.signature.isEmpty() && hook.signature != msg.signature())
1559 if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1561 if (!hook.argumentMatch.isEmpty()) {
1562 const QVariantList arguments = msg.arguments();
1563 if (hook.argumentMatch.size() > arguments.size())
1566 bool matched = true;
1567 for (int i = 0; i < hook.argumentMatch.size(); ++i) {
1568 const QString ¶m = hook.argumentMatch.at(i);
1570 continue; // don't try to match against this
1571 if (param == arguments.at(i).toString())
1572 continue; // matched
1580 activateSignal(hook, msg);
1584 void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1586 // We call handlesignal(QString, QDBusMessage) three times:
1587 // one with member:interface
1589 // one with :interface
1590 // This allows us to match signals with wildcards on member or interface
1593 QString key = msg.member();
1594 key.reserve(key.length() + 1 + msg.interface().length());
1595 key += QLatin1Char(':');
1596 key += msg.interface();
1598 QDBusReadLocker locker(HandleSignalAction, this);
1599 handleSignal(key, msg); // one try
1601 key.truncate(msg.member().length() + 1); // keep the ':'
1602 handleSignal(key, msg); // second try
1604 key = QLatin1Char(':');
1605 key += msg.interface();
1606 handleSignal(key, msg); // third try
1609 static dbus_int32_t server_slot = -1;
1611 void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
1621 dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
1622 if (data_allocated && server_slot < 0)
1625 dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
1630 //qDebug() << "watch_functions_set" << watch_functions_set;
1631 Q_UNUSED(watch_functions_set);
1633 dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
1638 //qDebug() << "time_functions_set" << time_functions_set;
1639 Q_UNUSED(time_functions_set);
1641 q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1643 dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
1644 //qDebug() << "data_set" << data_set;
1648 void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
1658 q_dbus_connection_set_exit_on_disconnect(connection, false);
1659 q_dbus_connection_set_watch_functions(connection,
1664 q_dbus_connection_set_timeout_functions(connection,
1669 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1670 q_dbus_connection_add_filter(connection,
1674 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1677 static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnection *connection)
1679 QDBusConnection::ConnectionCapabilities result = 0;
1681 #if defined(QT_LINKED_LIBDBUS) && DBUS_VERSION < 0x010400
1682 // no capabilities are possible
1684 # if !defined(QT_LINKED_LIBDBUS)
1685 // run-time check if the next functions are available
1686 int major, minor, micro;
1687 q_dbus_get_version(&major, &minor, µ);
1688 if (major == 1 && minor < 4)
1692 #ifndef DBUS_TYPE_UNIX_FD
1693 # define DBUS_TYPE_UNIX_FD int('h')
1695 if (q_dbus_connection_can_send_type(connection, DBUS_TYPE_UNIX_FD))
1696 result |= QDBusConnection::UnixFileDescriptorPassing;
1702 void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
1712 const char *service = q_dbus_bus_get_unique_name(connection);
1714 baseService = QString::fromUtf8(service);
1715 capabilities = connectionCapabilies(connection);
1717 q_dbus_connection_set_exit_on_disconnect(connection, false);
1718 q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1719 qDBusToggleWatch, this, 0);
1720 q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1721 qDBusToggleTimeout, this, 0);
1722 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1723 q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1725 // Initialize the hooks for the NameAcquired and NameLost signals
1726 // we don't use connectSignal here because we don't need the rules to be sent to the bus
1727 // the bus will always send us these two signals
1729 hook.service = dbusServiceString();
1730 hook.path.clear(); // no matching
1732 hook.params << QMetaType::Void << QVariant::String; // both functions take a QString as parameter and return void
1734 hook.midx = staticMetaObject.indexOfSlot("registerServiceNoLock(QString)");
1735 Q_ASSERT(hook.midx != -1);
1736 signalHooks.insert(QLatin1String("NameAcquired:" DBUS_INTERFACE_DBUS), hook);
1738 hook.midx = staticMetaObject.indexOfSlot("unregisterServiceNoLock(QString)");
1739 Q_ASSERT(hook.midx != -1);
1740 signalHooks.insert(QLatin1String("NameLost:" DBUS_INTERFACE_DBUS), hook);
1742 qDBusDebug() << this << ": connected successfully";
1744 // schedule a dispatch:
1745 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1749 static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1751 QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
1752 Q_ASSERT(call->pending == pending);
1754 QDBusConnectionPrivate::processFinishedCall(call);
1758 void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
1760 Q_ASSERT(pcall->pending);
1761 Q_ASSERT(!pcall->autoDelete);
1762 //Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
1764 if (pcall->waitingForFinished) {
1765 // another thread is already waiting
1766 pcall->waitForFinishedCondition.wait(&pcall->mutex);
1768 pcall->waitingForFinished = true;
1769 pcall->mutex.unlock();
1772 QDBusDispatchLocker locker(PendingCallBlockAction, this);
1773 q_dbus_pending_call_block(pcall->pending);
1774 // QDBusConnectionPrivate::processFinishedCall() is called automatically
1776 pcall->mutex.lock();
1780 void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
1782 QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1784 QMutexLocker locker(&call->mutex);
1786 QDBusMessage &msg = call->replyMessage;
1787 if (call->pending) {
1788 // decode the message
1789 DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
1790 msg = QDBusMessagePrivate::fromDBusMessage(reply, connection->capabilities);
1791 q_dbus_message_unref(reply);
1793 qDBusDebug() << connection << "got message reply (async):" << msg;
1795 // Check if the reply has the expected signature
1796 call->checkReceivedSignature();
1798 if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
1799 // Deliver the return values of a remote function call.
1801 // There is only one connection and it is specified by idx
1802 // The slot must have the same parameter types that the message does
1803 // The slot may have less parameters than the message
1804 // The slot may optionally have one final parameter that is QDBusMessage
1805 // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1807 QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
1808 call->metaTypes, msg);
1810 connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
1812 qDBusDebug() << "Deliver failed!";
1816 q_dbus_pending_call_unref(call->pending);
1821 // Are there any watchers?
1822 if (call->watcherHelper)
1823 call->watcherHelper->emitSignals(msg, call->sentMessage);
1825 if (msg.type() == QDBusMessage::ErrorMessage)
1826 emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
1828 if (call->autoDelete) {
1829 Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
1834 int QDBusConnectionPrivate::send(const QDBusMessage& message)
1836 if (QDBusMessagePrivate::isLocal(message))
1837 return -1; // don't send; the reply will be retrieved by the caller
1838 // through the d_ptr->localReply link
1841 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1843 if (message.type() == QDBusMessage::MethodCallMessage)
1844 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1845 qPrintable(message.service()), qPrintable(message.path()),
1846 qPrintable(message.interface()), qPrintable(message.member()),
1847 qPrintable(error.message()));
1848 else if (message.type() == QDBusMessage::SignalMessage)
1849 qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
1850 qPrintable(message.path()), qPrintable(message.interface()),
1851 qPrintable(message.member()),
1852 qPrintable(error.message()));
1854 qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
1855 message.type() == QDBusMessage::ReplyMessage ? "reply" :
1856 message.type() == QDBusMessage::ErrorMessage ? "error" :
1857 "invalid", qPrintable(message.service()),
1858 qPrintable(error.message()));
1863 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1865 qDBusDebug() << this << "sending message (no reply):" << message;
1867 bool isOk = q_dbus_connection_send(connection, msg, 0);
1870 serial = q_dbus_message_get_serial(msg);
1872 q_dbus_message_unref(msg);
1876 QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1877 int sendMode, int timeout)
1880 if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
1881 && isServiceRegisteredByThread(message.service()))
1882 // special case for synchronous local calls
1883 return sendWithReplyLocal(message);
1885 if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
1887 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &err);
1889 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1890 qPrintable(message.service()), qPrintable(message.path()),
1891 qPrintable(message.interface()), qPrintable(message.member()),
1892 qPrintable(err.message()));
1894 return QDBusMessage::createError(err);
1897 qDBusDebug() << this << "sending message (blocking):" << message;
1898 QDBusErrorInternal error;
1899 DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
1901 q_dbus_message_unref(msg);
1904 lastError = err = error;
1905 return QDBusMessage::createError(err);
1908 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply, capabilities);
1909 q_dbus_message_unref(reply);
1910 qDBusDebug() << this << "got message reply (blocking):" << amsg;
1913 } else { // use the event loop
1914 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1917 if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
1918 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
1920 loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
1921 loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
1923 // enter the event loop and wait for a reply
1924 loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1927 QDBusMessage reply = pcall->replyMessage;
1928 lastError = QDBusError(reply); // set or clear error
1935 QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
1937 qDBusDebug() << this << "sending message via local-loop:" << message;
1939 QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
1940 bool handled = handleMessage(localCallMsg);
1943 QString interface = message.interface();
1944 if (interface.isEmpty())
1945 interface = QLatin1String("<no-interface>");
1946 return QDBusMessage::createError(QDBusError::InternalError,
1947 QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
1948 .arg(interface, message.member(),
1949 message.path(), message.signature()));
1952 // if the message was handled, there might be a reply
1953 QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
1954 if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
1955 qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
1956 "on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
1957 qPrintable(message.signature()));
1958 return QDBusMessage::createError(
1959 QDBusError(QDBusError::InternalError,
1960 QLatin1String("local-loop message cannot have delayed replies")));
1964 qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
1965 return localReplyMsg;
1968 QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
1971 if (isServiceRegisteredByThread(message.service())) {
1972 // special case for local calls
1973 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1974 pcall->replyMessage = sendWithReplyLocal(message);
1980 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1981 pcall->ref.store(0);
1984 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1986 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1987 qPrintable(message.service()), qPrintable(message.path()),
1988 qPrintable(message.interface()), qPrintable(message.member()),
1989 qPrintable(error.message()));
1990 pcall->replyMessage = QDBusMessage::createError(error);
1995 qDBusDebug() << this << "sending message (async):" << message;
1996 DBusPendingCall *pending = 0;
1998 QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
1999 if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
2001 q_dbus_message_unref(msg);
2003 pcall->pending = pending;
2004 q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
2008 // we're probably disconnected at this point
2009 lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
2012 lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
2015 q_dbus_message_unref(msg);
2016 pcall->replyMessage = QDBusMessage::createError(error);
2020 int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
2021 const char *returnMethod, const char *errorMethod,
2024 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
2027 // has it already finished with success (dispatched locally)?
2028 if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
2029 pcall->setReplyCallback(receiver, returnMethod);
2030 processFinishedCall(pcall);
2035 // either it hasn't finished or it has finished with error
2037 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
2038 connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
2039 Qt::QueuedConnection);
2040 pcall->watcherHelper->moveToThread(thread());
2043 // has it already finished and is an error reply message?
2044 if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
2045 processFinishedCall(pcall);
2050 pcall->autoDelete = true;
2052 pcall->setReplyCallback(receiver, returnMethod);
2057 bool QDBusConnectionPrivate::connectSignal(const QString &service,
2058 const QString &path, const QString &interface, const QString &name,
2059 const QStringList &argumentMatch, const QString &signature,
2060 QObject *receiver, const char *slot)
2063 QDBusConnectionPrivate::SignalHook hook;
2065 QString name2 = name;
2069 hook.signature = signature;
2070 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2071 return false; // don't connect
2073 // avoid duplicating:
2074 QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.find(key);
2075 QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
2076 for ( ; it != end && it.key() == key; ++it) {
2077 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2078 if (entry.service == hook.service &&
2079 entry.path == hook.path &&
2080 entry.signature == hook.signature &&
2081 entry.obj == hook.obj &&
2082 entry.midx == hook.midx &&
2083 entry.argumentMatch == hook.argumentMatch) {
2084 // no need to compare the parameters if it's the same slot
2085 return true; // already there
2089 connectSignal(key, hook);
2093 void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
2095 signalHooks.insertMulti(key, hook);
2096 connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2097 Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
2099 MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
2101 if (it != matchRefCounts.end()) { // Match already present
2102 it.value() = it.value() + 1;
2106 matchRefCounts.insert(hook.matchRule, 1);
2109 if (mode != QDBusConnectionPrivate::PeerMode) {
2110 qDBusDebug("Adding rule: %s", hook.matchRule.constData());
2111 q_dbus_bus_add_match(connection, hook.matchRule, NULL);
2113 // Successfully connected the signal
2114 // Do we need to watch for this name?
2115 if (shouldWatchService(hook.service)) {
2116 WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
2117 if (++data.refcount == 1) {
2118 // we need to watch for this service changing
2119 connectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2120 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2121 this, SLOT(serviceOwnerChangedNoLock(QString,QString,QString)));
2122 data.owner = getNameOwnerNoCache(hook.service);
2123 qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
2124 << data.owner << ")";
2131 bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
2132 const QString &path, const QString &interface, const QString &name,
2133 const QStringList &argumentMatch, const QString &signature,
2134 QObject *receiver, const char *slot)
2137 QDBusConnectionPrivate::SignalHook hook;
2139 QString name2 = name;
2143 hook.signature = signature;
2144 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2145 return false; // don't disconnect
2147 // avoid duplicating:
2148 QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
2149 QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
2150 for ( ; it != end && it.key() == key; ++it) {
2151 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2152 if (entry.service == hook.service &&
2153 entry.path == hook.path &&
2154 entry.signature == hook.signature &&
2155 entry.obj == hook.obj &&
2156 entry.midx == hook.midx &&
2157 entry.argumentMatch == hook.argumentMatch) {
2158 // no need to compare the parameters if it's the same slot
2159 disconnectSignal(it);
2160 return true; // it was there
2164 // the slot was not found
2168 QDBusConnectionPrivate::SignalHookHash::Iterator
2169 QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
2171 const SignalHook &hook = it.value();
2174 MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
2175 if (i == matchRefCounts.end()) {
2176 qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
2178 if (i.value() == 1) {
2180 matchRefCounts.erase(i);
2183 i.value() = i.value() - 1;
2187 // we don't care about errors here
2188 if (connection && erase) {
2189 if (mode != QDBusConnectionPrivate::PeerMode) {
2190 qDBusDebug("Removing rule: %s", hook.matchRule.constData());
2191 q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
2193 // Successfully disconnected the signal
2194 // Were we watching for this name?
2195 WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
2196 if (sit != watchedServices.end()) {
2197 if (--sit.value().refcount == 0) {
2198 watchedServices.erase(sit);
2199 disconnectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2200 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2201 this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
2208 return signalHooks.erase(it);
2211 void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
2213 connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2214 Qt::DirectConnection);
2216 if (node->flags & (QDBusConnection::ExportAdaptors
2217 | QDBusConnection::ExportScriptableSignals
2218 | QDBusConnection::ExportNonScriptableSignals)) {
2219 QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
2221 if (node->flags & (QDBusConnection::ExportScriptableSignals
2222 | QDBusConnection::ExportNonScriptableSignals)) {
2223 connector->disconnectAllSignals(node->obj);
2224 connector->connectAllSignals(node->obj);
2227 // disconnect and reconnect to avoid duplicates
2228 connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2229 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
2230 connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2231 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2232 Qt::DirectConnection);
2236 void QDBusConnectionPrivate::connectRelay(const QString &service,
2237 const QString &path, const QString &interface,
2238 QDBusAbstractInterface *receiver,
2239 const QMetaMethod &signal)
2241 // this function is called by QDBusAbstractInterface when one of its signals is connected
2242 // we set up a relay from D-Bus into it
2247 sig.append(QSIGNAL_CODE + '0');
2248 sig.append(signal.methodSignature());
2249 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, sig,
2250 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2251 return; // don't connect
2253 // add it to our list:
2254 QDBusWriteLocker locker(ConnectRelayAction, this);
2255 SignalHookHash::ConstIterator it = signalHooks.find(key);
2256 SignalHookHash::ConstIterator end = signalHooks.constEnd();
2257 for ( ; it != end && it.key() == key; ++it) {
2258 const SignalHook &entry = it.value();
2259 if (entry.service == hook.service &&
2260 entry.path == hook.path &&
2261 entry.signature == hook.signature &&
2262 entry.obj == hook.obj &&
2263 entry.midx == hook.midx)
2264 return; // already there, no need to re-add
2267 connectSignal(key, hook);
2270 void QDBusConnectionPrivate::disconnectRelay(const QString &service,
2271 const QString &path, const QString &interface,
2272 QDBusAbstractInterface *receiver,
2273 const QMetaMethod &signal)
2275 // this function is called by QDBusAbstractInterface when one of its signals is disconnected
2276 // we remove relay from D-Bus into it
2281 sig.append(QSIGNAL_CODE + '0');
2282 sig.append(signal.methodSignature());
2283 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, sig,
2284 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2285 return; // don't connect
2287 // remove it from our list:
2288 QDBusWriteLocker locker(DisconnectRelayAction, this);
2289 SignalHookHash::Iterator it = signalHooks.find(key);
2290 SignalHookHash::Iterator end = signalHooks.end();
2291 for ( ; it != end && it.key() == key; ++it) {
2292 const SignalHook &entry = it.value();
2293 if (entry.service == hook.service &&
2294 entry.path == hook.path &&
2295 entry.signature == hook.signature &&
2296 entry.obj == hook.obj &&
2297 entry.midx == hook.midx) {
2299 disconnectSignal(it);
2304 qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
2307 QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
2309 if (QDBusUtil::isValidUniqueConnectionName(serviceName))
2315 // acquire a read lock for the cache
2316 QReadLocker locker(&lock);
2317 WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
2318 if (it != watchedServices.constEnd())
2323 return getNameOwnerNoCache(serviceName);
2326 QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
2328 QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2329 QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2330 QLatin1String("GetNameOwner"));
2331 QDBusMessagePrivate::setParametersValidated(msg, true);
2333 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2334 if (reply.type() == QDBusMessage::ReplyMessage)
2335 return reply.arguments().at(0).toString();
2340 QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
2341 const QString &interface, QDBusError &error)
2343 // service must be a unique connection name
2344 if (!interface.isEmpty()) {
2345 QDBusReadLocker locker(FindMetaObject1Action, this);
2346 QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
2351 // introspect the target object
2352 QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
2353 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
2354 QLatin1String("Introspect"));
2355 QDBusMessagePrivate::setParametersValidated(msg, true);
2357 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2359 // it doesn't exist yet, we have to create it
2360 QDBusWriteLocker locker(FindMetaObject2Action, this);
2361 QDBusMetaObject *mo = 0;
2362 if (!interface.isEmpty())
2363 mo = cachedMetaObjects.value(interface, 0);
2365 // maybe it got created when we switched from read to write lock
2369 if (reply.type() == QDBusMessage::ReplyMessage) {
2370 if (reply.signature() == QLatin1String("s"))
2371 // fetch the XML description
2372 xml = reply.arguments().at(0).toString();
2374 error = QDBusError(reply);
2376 if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
2380 // release the lock and return
2381 QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
2382 cachedMetaObjects, error);
2387 void QDBusConnectionPrivate::registerService(const QString &serviceName)
2389 QDBusWriteLocker locker(RegisterServiceAction, this);
2390 registerServiceNoLock(serviceName);
2393 void QDBusConnectionPrivate::registerServiceNoLock(const QString &serviceName)
2395 serviceNames.append(serviceName);
2398 void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
2400 QDBusWriteLocker locker(UnregisterServiceAction, this);
2401 unregisterServiceNoLock(serviceName);
2404 void QDBusConnectionPrivate::unregisterServiceNoLock(const QString &serviceName)
2406 serviceNames.removeAll(serviceName);
2409 bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
2411 if (!serviceName.isEmpty() && serviceName == baseService)
2413 QStringList copy = serviceNames;
2414 return copy.contains(serviceName);
2417 void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
2419 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
2420 QCoreApplication::postEvent(object, ev);
2421 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
2426 #endif // QT_NO_DBUS