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 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator 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)
1051 qDBusDebug() << this << "Disconnected";
1054 void QDBusConnectionPrivate::checkThread()
1057 if (QCoreApplication::instance())
1058 moveToThread(QCoreApplication::instance()->thread());
1060 qWarning("The thread that had QDBusConnection('%s') has died and there is no main thread",
1065 bool QDBusConnectionPrivate::handleError(const QDBusErrorInternal &error)
1068 return false; // no error
1070 //lock.lockForWrite();
1076 void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
1079 QDBusWatchAndTimeoutLocker locker(TimerEventAction, this);
1080 DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
1082 q_dbus_timeout_handle(timeout);
1088 void QDBusConnectionPrivate::customEvent(QEvent *e)
1090 Q_ASSERT(e->type() == QEvent::User);
1092 QDBusConnectionCallbackEvent *ev = static_cast<QDBusConnectionCallbackEvent *>(e);
1093 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1094 QDBusLockerBase::BeforeDeliver, this);
1095 switch (ev->subtype)
1097 case QDBusConnectionCallbackEvent::AddTimeout: {
1098 QDBusWatchAndTimeoutLocker locker(RealAddTimeoutAction, this);
1099 while (!timeoutsPendingAdd.isEmpty()) {
1100 QPair<DBusTimeout *, int> entry = timeoutsPendingAdd.takeFirst();
1101 qDBusRealAddTimeout(this, entry.first, entry.second);
1106 case QDBusConnectionCallbackEvent::KillTimer:
1107 killTimer(ev->timerId);
1110 case QDBusConnectionCallbackEvent::AddWatch:
1111 qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
1114 case QDBusConnectionCallbackEvent::ToggleWatch:
1115 qDBusRealToggleWatch(this, ev->watch, ev->fd);
1118 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1119 QDBusLockerBase::AfterDeliver, this);
1122 void QDBusConnectionPrivate::doDispatch()
1124 QDBusDispatchLocker locker(DoDispatchAction, this);
1125 if (mode == ClientMode || mode == PeerMode)
1126 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
1129 void QDBusConnectionPrivate::socketRead(int fd)
1131 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1134 QDBusWatchAndTimeoutLocker locker(SocketReadAction, this);
1135 WatcherHash::ConstIterator it = watchers.constFind(fd);
1136 while (it != watchers.constEnd() && it.key() == fd) {
1137 if (it->watch && it->read && it->read->isEnabled())
1138 pendingWatches.append(it.value().watch);
1143 for (int i = 0; i < pendingWatches.size(); ++i)
1144 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_READABLE))
1145 qDebug("OUT OF MEM");
1149 void QDBusConnectionPrivate::socketWrite(int fd)
1151 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1154 QDBusWatchAndTimeoutLocker locker(SocketWriteAction, this);
1155 WatcherHash::ConstIterator it = watchers.constFind(fd);
1156 while (it != watchers.constEnd() && it.key() == fd) {
1157 if (it->watch && it->write && it->write->isEnabled())
1158 pendingWatches.append(it.value().watch);
1163 for (int i = 0; i < pendingWatches.size(); ++i)
1164 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_WRITABLE))
1165 qDebug("OUT OF MEM");
1168 void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
1170 QDBusWriteLocker locker(ObjectDestroyedAction, this);
1171 huntAndDestroy(obj, rootNode);
1173 SignalHookHash::iterator sit = signalHooks.begin();
1174 while (sit != signalHooks.end()) {
1175 if (static_cast<QObject *>(sit.value().obj) == obj)
1176 sit = disconnectSignal(sit);
1181 obj->disconnect(this);
1184 void QDBusConnectionPrivate::relaySignal(QObject *obj, const QMetaObject *mo, int signalId,
1185 const QVariantList &args)
1187 QString interface = qDBusInterfaceFromMetaObject(mo);
1189 QMetaMethod mm = mo->method(signalId);
1190 QByteArray memberName = mm.name();
1192 // check if it's scriptable
1193 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
1194 bool isAdaptor = false;
1195 for ( ; mo; mo = mo->superClass())
1196 if (mo == &QDBusAbstractAdaptor::staticMetaObject) {
1201 QDBusReadLocker locker(RelaySignalAction, this);
1202 QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/"), interface,
1203 QLatin1String(memberName));
1204 QDBusMessagePrivate::setParametersValidated(message, true);
1205 message.setArguments(args);
1207 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1209 qWarning("QDBusConnection: Could not emit signal %s.%s: %s", qPrintable(interface), memberName.constData(),
1210 qPrintable(error.message()));
1215 //qDBusDebug() << "Emitting signal" << message;
1216 //qDBusDebug() << "for paths:";
1217 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1218 huntAndEmit(connection, msg, obj, rootNode, isScriptable, isAdaptor);
1219 q_dbus_message_unref(msg);
1222 void QDBusConnectionPrivate::serviceOwnerChangedNoLock(const QString &name,
1223 const QString &oldOwner, const QString &newOwner)
1226 // QDBusWriteLocker locker(UpdateSignalHookOwnerAction, this);
1227 WatchedServicesHash::Iterator it = watchedServices.find(name);
1228 if (it == watchedServices.end())
1230 if (oldOwner != it->owner)
1231 qWarning("QDBusConnection: name '%s' had owner '%s' but we thought it was '%s'",
1232 qPrintable(name), qPrintable(oldOwner), qPrintable(it->owner));
1234 qDBusDebug() << this << "Updating name" << name << "from" << oldOwner << "to" << newOwner;
1235 it->owner = newOwner;
1238 int QDBusConnectionPrivate::findSlot(QObject* obj, const QByteArray &normalizedName,
1239 QVector<int> ¶ms)
1241 int midx = obj->metaObject()->indexOfMethod(normalizedName);
1245 int inputCount = qDBusParametersForMethod(obj->metaObject()->method(midx), params);
1246 if ( inputCount == -1 || inputCount + 1 != params.count() )
1247 return -1; // failed to parse or invalid arguments or output arguments
1252 bool QDBusConnectionPrivate::prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
1253 const QString &service,
1254 const QString &path, const QString &interface, const QString &name,
1255 const QStringList &argMatch,
1256 QObject *receiver, const char *signal, int minMIdx,
1257 bool buildSignature)
1259 QByteArray normalizedName = signal + 1;
1260 hook.midx = findSlot(receiver, signal + 1, hook.params);
1261 if (hook.midx == -1) {
1262 normalizedName = QMetaObject::normalizedSignature(signal + 1);
1263 hook.midx = findSlot(receiver, normalizedName, hook.params);
1265 if (hook.midx < minMIdx) {
1266 if (hook.midx == -1)
1271 hook.service = service;
1273 hook.obj = receiver;
1274 hook.argumentMatch = argMatch;
1276 // build the D-Bus signal name and signature
1277 // This should not happen for QDBusConnection::connect, use buildSignature here, since
1278 // QDBusConnection::connect passes false and everything else uses true
1279 QString mname = name;
1280 if (buildSignature && mname.isNull()) {
1281 normalizedName.truncate(normalizedName.indexOf('('));
1282 mname = QString::fromUtf8(normalizedName);
1285 key.reserve(interface.length() + 1 + mname.length());
1286 key += QLatin1Char(':');
1289 if (buildSignature) {
1290 hook.signature.clear();
1291 for (int i = 1; i < hook.params.count(); ++i)
1292 if (hook.params.at(i) != QDBusMetaTypeId::message)
1293 hook.signature += QLatin1String( QDBusMetaType::typeToSignature( hook.params.at(i) ) );
1296 hook.matchRule = buildMatchRule(service, path, interface, mname, argMatch, hook.signature);
1297 return true; // connect to this signal
1300 void QDBusConnectionPrivate::sendError(const QDBusMessage &msg, QDBusError::ErrorType code)
1302 if (code == QDBusError::UnknownMethod) {
1303 QString interfaceMsg;
1304 if (msg.interface().isEmpty())
1305 interfaceMsg = QLatin1String("any interface");
1307 interfaceMsg = QString::fromLatin1("interface '%1'").arg(msg.interface());
1309 send(msg.createErrorReply(code,
1310 QString::fromLatin1("No such method '%1' in %2 at object path '%3' "
1312 .arg(msg.member(), interfaceMsg, msg.path(), msg.signature())));
1313 } else if (code == QDBusError::UnknownInterface) {
1314 send(msg.createErrorReply(QDBusError::UnknownInterface,
1315 QString::fromLatin1("No such interface '%1' at object path '%2'")
1316 .arg(msg.interface(), msg.path())));
1317 } else if (code == QDBusError::UnknownObject) {
1318 send(msg.createErrorReply(QDBusError::UnknownObject,
1319 QString::fromLatin1("No such object path '%1'").arg(msg.path())));
1323 bool QDBusConnectionPrivate::activateInternalFilters(const ObjectTreeNode &node,
1324 const QDBusMessage &msg)
1326 // object may be null
1327 const QString interface = msg.interface();
1329 if (interface.isEmpty() || interface == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE)) {
1330 if (msg.member() == QLatin1String("Introspect") && msg.signature().isEmpty()) {
1331 //qDebug() << "QDBusConnectionPrivate::activateInternalFilters introspect" << msg.d_ptr->msg;
1332 QDBusMessage reply = msg.createReply(qDBusIntrospectObject(node, msg.path()));
1337 if (!interface.isEmpty()) {
1338 sendError(msg, QDBusError::UnknownMethod);
1343 if (node.obj && (interface.isEmpty() ||
1344 interface == QLatin1String(DBUS_INTERFACE_PROPERTIES))) {
1345 //qDebug() << "QDBusConnectionPrivate::activateInternalFilters properties" << msg.d_ptr->msg;
1346 if (msg.member() == QLatin1String("Get") && msg.signature() == QLatin1String("ss")) {
1347 QDBusMessage reply = qDBusPropertyGet(node, msg);
1350 } else if (msg.member() == QLatin1String("Set") && msg.signature() == QLatin1String("ssv")) {
1351 QDBusMessage reply = qDBusPropertySet(node, msg);
1354 } else if (msg.member() == QLatin1String("GetAll") && msg.signature() == QLatin1String("s")) {
1355 QDBusMessage reply = qDBusPropertyGetAll(node, msg);
1360 if (!interface.isEmpty()) {
1361 sendError(msg, QDBusError::UnknownMethod);
1369 void QDBusConnectionPrivate::activateObject(ObjectTreeNode &node, const QDBusMessage &msg,
1372 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call to a slot
1375 // The call is routed through the adaptor sub-objects if we have any
1377 // object may be null
1379 if (node.flags & QDBusConnectionPrivate::VirtualObject) {
1380 if (node.treeNode->handleMessage(msg, q(this))) {
1383 if (activateInternalFilters(node, msg))
1388 if (pathStartPos != msg.path().length()) {
1389 node.flags &= ~QDBusConnection::ExportAllSignals;
1390 node.obj = findChildObject(&node, msg.path(), pathStartPos);
1392 sendError(msg, QDBusError::UnknownObject);
1397 QDBusAdaptorConnector *connector;
1398 if (node.flags & QDBusConnection::ExportAdaptors &&
1399 (connector = qDBusFindAdaptorConnector(node.obj))) {
1400 int newflags = node.flags | QDBusConnection::ExportAllSlots;
1402 if (msg.interface().isEmpty()) {
1403 // place the call in all interfaces
1404 // let the first one that handles it to work
1405 QDBusAdaptorConnector::AdaptorMap::ConstIterator it =
1406 connector->adaptors.constBegin();
1407 QDBusAdaptorConnector::AdaptorMap::ConstIterator end =
1408 connector->adaptors.constEnd();
1410 for ( ; it != end; ++it)
1411 if (activateCall(it->adaptor, newflags, msg))
1414 // check if we have an interface matching the name that was asked:
1415 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
1416 it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
1418 if (it != connector->adaptors.constEnd() && msg.interface() == QLatin1String(it->interface)) {
1419 if (!activateCall(it->adaptor, newflags, msg))
1420 sendError(msg, QDBusError::UnknownMethod);
1426 // no adaptors matched or were exported
1427 // try our standard filters
1428 if (activateInternalFilters(node, msg))
1429 return; // internal filters have already run or an error has been sent
1431 // try the object itself:
1432 if (node.flags & (QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportNonScriptableSlots) ||
1433 node.flags & (QDBusConnection::ExportScriptableInvokables|QDBusConnection::ExportNonScriptableInvokables)) {
1434 bool interfaceFound = true;
1435 if (!msg.interface().isEmpty())
1436 interfaceFound = qDBusInterfaceInObject(node.obj, msg.interface());
1438 if (interfaceFound) {
1439 if (!activateCall(node.obj, node.flags, msg))
1440 sendError(msg, QDBusError::UnknownMethod);
1445 // nothing matched, send an error code
1446 if (msg.interface().isEmpty())
1447 sendError(msg, QDBusError::UnknownMethod);
1449 sendError(msg, QDBusError::UnknownInterface);
1452 void QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
1454 // if the msg is external, we were called from inside doDispatch
1455 // that means the dispatchLock mutex is locked
1456 // must not call out to user code in that case
1458 // however, if the message is internal, handleMessage was called
1459 // directly and no lock is in place. We can therefore call out to
1460 // user code, if necessary
1461 ObjectTreeNode result;
1463 QThread *objThread = 0;
1468 QDBusReadLocker locker(HandleObjectCallAction, this);
1469 if (!findObject(&rootNode, msg.path(), usedLength, result)) {
1470 // qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
1471 sendError(msg, QDBusError::UnknownObject);
1476 // no object -> no threading issues
1477 // it's either going to be an error, or an internal filter
1478 activateObject(result, msg, usedLength);
1482 objThread = result.obj->thread();
1484 send(msg.createErrorReply(QDBusError::InternalError,
1485 QString::fromLatin1("Object '%1' (at path '%2')"
1486 " has no thread. Cannot deliver message.")
1487 .arg(result.obj->objectName(), msg.path())));
1491 if (!QDBusMessagePrivate::isLocal(msg)) {
1492 // external incoming message
1493 // post it and forget
1494 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1495 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1498 } else if (objThread != QThread::currentThread()) {
1499 // synchronize with other thread
1500 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1501 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1502 usedLength, msg, &sem));
1507 } // release the lock
1510 SEM_ACQUIRE(HandleObjectCallSemaphoreAction, sem);
1512 activateObject(result, msg, usedLength);
1515 QDBusActivateObjectEvent::~QDBusActivateObjectEvent()
1518 // we're being destroyed without delivering
1519 // it means the object was deleted between posting and delivering
1520 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1521 that->sendError(message, QDBusError::UnknownObject);
1524 // semaphore releasing happens in ~QMetaCallEvent
1527 void QDBusActivateObjectEvent::placeMetaCall(QObject *)
1529 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1531 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1532 QDBusLockerBase::BeforeDeliver, that);
1533 that->activateObject(node, message, pathStartPos);
1534 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1535 QDBusLockerBase::AfterDeliver, that);
1540 void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1542 SignalHookHash::const_iterator it = signalHooks.constFind(key);
1543 SignalHookHash::const_iterator end = signalHooks.constEnd();
1544 //qDebug("looking for: %s", path.toLocal8Bit().constData());
1545 //qDBusDebug() << signalHooks.keys();
1546 for ( ; it != end && it.key() == key; ++it) {
1547 const SignalHook &hook = it.value();
1548 if (!hook.service.isEmpty()) {
1549 const QString owner =
1550 shouldWatchService(hook.service) ?
1551 watchedServices.value(hook.service).owner :
1553 if (owner != msg.service())
1556 if (!hook.path.isEmpty() && hook.path != msg.path())
1558 if (!hook.signature.isEmpty() && hook.signature != msg.signature())
1560 if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1562 if (!hook.argumentMatch.isEmpty()) {
1563 const QVariantList arguments = msg.arguments();
1564 if (hook.argumentMatch.size() > arguments.size())
1567 bool matched = true;
1568 for (int i = 0; i < hook.argumentMatch.size(); ++i) {
1569 const QString ¶m = hook.argumentMatch.at(i);
1571 continue; // don't try to match against this
1572 if (param == arguments.at(i).toString())
1573 continue; // matched
1581 activateSignal(hook, msg);
1585 void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1587 // We call handlesignal(QString, QDBusMessage) three times:
1588 // one with member:interface
1590 // one with :interface
1591 // This allows us to match signals with wildcards on member or interface
1594 QString key = msg.member();
1595 key.reserve(key.length() + 1 + msg.interface().length());
1596 key += QLatin1Char(':');
1597 key += msg.interface();
1599 QDBusReadLocker locker(HandleSignalAction, this);
1600 handleSignal(key, msg); // one try
1602 key.truncate(msg.member().length() + 1); // keep the ':'
1603 handleSignal(key, msg); // second try
1605 key = QLatin1Char(':');
1606 key += msg.interface();
1607 handleSignal(key, msg); // third try
1610 static dbus_int32_t server_slot = -1;
1612 void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
1622 dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
1623 if (data_allocated && server_slot < 0)
1626 dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
1631 //qDebug() << "watch_functions_set" << watch_functions_set;
1632 Q_UNUSED(watch_functions_set);
1634 dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
1639 //qDebug() << "time_functions_set" << time_functions_set;
1640 Q_UNUSED(time_functions_set);
1642 q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1644 dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
1645 //qDebug() << "data_set" << data_set;
1649 void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
1659 q_dbus_connection_set_exit_on_disconnect(connection, false);
1660 q_dbus_connection_set_watch_functions(connection,
1665 q_dbus_connection_set_timeout_functions(connection,
1670 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1671 q_dbus_connection_add_filter(connection,
1675 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1678 static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnection *connection)
1680 QDBusConnection::ConnectionCapabilities result = 0;
1682 #if defined(QT_LINKED_LIBDBUS) && DBUS_VERSION < 0x010400
1683 // no capabilities are possible
1685 # if !defined(QT_LINKED_LIBDBUS)
1686 // run-time check if the next functions are available
1687 int major, minor, micro;
1688 q_dbus_get_version(&major, &minor, µ);
1689 if (major == 1 && minor < 4)
1693 #ifndef DBUS_TYPE_UNIX_FD
1694 # define DBUS_TYPE_UNIX_FD int('h')
1696 if (q_dbus_connection_can_send_type(connection, DBUS_TYPE_UNIX_FD))
1697 result |= QDBusConnection::UnixFileDescriptorPassing;
1703 void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
1713 const char *service = q_dbus_bus_get_unique_name(connection);
1715 baseService = QString::fromUtf8(service);
1716 capabilities = connectionCapabilies(connection);
1718 q_dbus_connection_set_exit_on_disconnect(connection, false);
1719 q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1720 qDBusToggleWatch, this, 0);
1721 q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1722 qDBusToggleTimeout, this, 0);
1723 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1724 q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1726 // Initialize the hooks for the NameAcquired and NameLost signals
1727 // we don't use connectSignal here because we don't need the rules to be sent to the bus
1728 // the bus will always send us these two signals
1730 hook.service = dbusServiceString();
1731 hook.path.clear(); // no matching
1733 hook.params << QMetaType::Void << QVariant::String; // both functions take a QString as parameter and return void
1735 hook.midx = staticMetaObject.indexOfSlot("registerServiceNoLock(QString)");
1736 Q_ASSERT(hook.midx != -1);
1737 signalHooks.insert(QLatin1String("NameAcquired:" DBUS_INTERFACE_DBUS), hook);
1739 hook.midx = staticMetaObject.indexOfSlot("unregisterServiceNoLock(QString)");
1740 Q_ASSERT(hook.midx != -1);
1741 signalHooks.insert(QLatin1String("NameLost:" DBUS_INTERFACE_DBUS), hook);
1743 qDBusDebug() << this << ": connected successfully";
1745 // schedule a dispatch:
1746 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1750 static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1752 QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
1753 Q_ASSERT(call->pending == pending);
1755 QDBusConnectionPrivate::processFinishedCall(call);
1759 void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
1761 Q_ASSERT(pcall->pending);
1762 Q_ASSERT(!pcall->autoDelete);
1763 //Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
1765 if (pcall->waitingForFinished) {
1766 // another thread is already waiting
1767 pcall->waitForFinishedCondition.wait(&pcall->mutex);
1769 pcall->waitingForFinished = true;
1770 pcall->mutex.unlock();
1773 QDBusDispatchLocker locker(PendingCallBlockAction, this);
1774 q_dbus_pending_call_block(pcall->pending);
1775 // QDBusConnectionPrivate::processFinishedCall() is called automatically
1777 pcall->mutex.lock();
1778 pcall->waitForFinishedCondition.wakeAll();
1782 void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
1784 QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1786 QMutexLocker locker(&call->mutex);
1788 QDBusMessage &msg = call->replyMessage;
1789 if (call->pending) {
1790 // decode the message
1791 DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
1792 msg = QDBusMessagePrivate::fromDBusMessage(reply, connection->capabilities);
1793 q_dbus_message_unref(reply);
1795 qDBusDebug() << connection << "got message reply (async):" << msg;
1797 // Check if the reply has the expected signature
1798 call->checkReceivedSignature();
1800 if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
1801 // Deliver the return values of a remote function call.
1803 // There is only one connection and it is specified by idx
1804 // The slot must have the same parameter types that the message does
1805 // The slot may have less parameters than the message
1806 // The slot may optionally have one final parameter that is QDBusMessage
1807 // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1809 QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
1810 call->metaTypes, msg);
1812 connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
1814 qDBusDebug() << "Deliver failed!";
1818 q_dbus_pending_call_unref(call->pending);
1823 // Are there any watchers?
1824 if (call->watcherHelper)
1825 call->watcherHelper->emitSignals(msg, call->sentMessage);
1827 if (msg.type() == QDBusMessage::ErrorMessage)
1828 emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
1830 if (call->autoDelete) {
1831 Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
1836 int QDBusConnectionPrivate::send(const QDBusMessage& message)
1838 if (QDBusMessagePrivate::isLocal(message))
1839 return -1; // don't send; the reply will be retrieved by the caller
1840 // through the d_ptr->localReply link
1843 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1845 if (message.type() == QDBusMessage::MethodCallMessage)
1846 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1847 qPrintable(message.service()), qPrintable(message.path()),
1848 qPrintable(message.interface()), qPrintable(message.member()),
1849 qPrintable(error.message()));
1850 else if (message.type() == QDBusMessage::SignalMessage)
1851 qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
1852 qPrintable(message.path()), qPrintable(message.interface()),
1853 qPrintable(message.member()),
1854 qPrintable(error.message()));
1856 qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
1857 message.type() == QDBusMessage::ReplyMessage ? "reply" :
1858 message.type() == QDBusMessage::ErrorMessage ? "error" :
1859 "invalid", qPrintable(message.service()),
1860 qPrintable(error.message()));
1865 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1867 qDBusDebug() << this << "sending message (no reply):" << message;
1869 bool isOk = q_dbus_connection_send(connection, msg, 0);
1872 serial = q_dbus_message_get_serial(msg);
1874 q_dbus_message_unref(msg);
1878 QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1879 int sendMode, int timeout)
1882 if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
1883 && isServiceRegisteredByThread(message.service()))
1884 // special case for synchronous local calls
1885 return sendWithReplyLocal(message);
1887 if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
1889 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &err);
1891 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1892 qPrintable(message.service()), qPrintable(message.path()),
1893 qPrintable(message.interface()), qPrintable(message.member()),
1894 qPrintable(err.message()));
1896 return QDBusMessage::createError(err);
1899 qDBusDebug() << this << "sending message (blocking):" << message;
1900 QDBusErrorInternal error;
1901 DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
1903 q_dbus_message_unref(msg);
1906 lastError = err = error;
1907 return QDBusMessage::createError(err);
1910 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply, capabilities);
1911 q_dbus_message_unref(reply);
1912 qDBusDebug() << this << "got message reply (blocking):" << amsg;
1915 } else { // use the event loop
1916 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1919 if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
1920 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
1922 loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
1923 loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
1925 // enter the event loop and wait for a reply
1926 loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1929 QDBusMessage reply = pcall->replyMessage;
1930 lastError = QDBusError(reply); // set or clear error
1937 QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
1939 qDBusDebug() << this << "sending message via local-loop:" << message;
1941 QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
1942 bool handled = handleMessage(localCallMsg);
1945 QString interface = message.interface();
1946 if (interface.isEmpty())
1947 interface = QLatin1String("<no-interface>");
1948 return QDBusMessage::createError(QDBusError::InternalError,
1949 QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
1950 .arg(interface, message.member(),
1951 message.path(), message.signature()));
1954 // if the message was handled, there might be a reply
1955 QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
1956 if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
1957 qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
1958 "on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
1959 qPrintable(message.signature()));
1960 return QDBusMessage::createError(
1961 QDBusError(QDBusError::InternalError,
1962 QLatin1String("local-loop message cannot have delayed replies")));
1966 qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
1967 return localReplyMsg;
1970 QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
1973 if (isServiceRegisteredByThread(message.service())) {
1974 // special case for local calls
1975 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1976 pcall->replyMessage = sendWithReplyLocal(message);
1982 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1983 pcall->ref.store(0);
1986 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1988 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1989 qPrintable(message.service()), qPrintable(message.path()),
1990 qPrintable(message.interface()), qPrintable(message.member()),
1991 qPrintable(error.message()));
1992 pcall->replyMessage = QDBusMessage::createError(error);
1997 qDBusDebug() << this << "sending message (async):" << message;
1998 DBusPendingCall *pending = 0;
2000 QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
2001 if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
2003 q_dbus_message_unref(msg);
2005 pcall->pending = pending;
2006 q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
2010 // we're probably disconnected at this point
2011 lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
2014 lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
2017 q_dbus_message_unref(msg);
2018 pcall->replyMessage = QDBusMessage::createError(error);
2022 int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
2023 const char *returnMethod, const char *errorMethod,
2026 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
2029 // has it already finished with success (dispatched locally)?
2030 if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
2031 pcall->setReplyCallback(receiver, returnMethod);
2032 processFinishedCall(pcall);
2037 // either it hasn't finished or it has finished with error
2039 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
2040 connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
2041 Qt::QueuedConnection);
2042 pcall->watcherHelper->moveToThread(thread());
2045 // has it already finished and is an error reply message?
2046 if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
2047 processFinishedCall(pcall);
2052 pcall->autoDelete = true;
2054 pcall->setReplyCallback(receiver, returnMethod);
2059 bool QDBusConnectionPrivate::connectSignal(const QString &service,
2060 const QString &path, const QString &interface, const QString &name,
2061 const QStringList &argumentMatch, const QString &signature,
2062 QObject *receiver, const char *slot)
2065 QDBusConnectionPrivate::SignalHook hook;
2067 QString name2 = name;
2071 hook.signature = signature;
2072 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2073 return false; // don't connect
2075 // avoid duplicating:
2076 QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.constFind(key);
2077 QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
2078 for ( ; it != end && it.key() == key; ++it) {
2079 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2080 if (entry.service == hook.service &&
2081 entry.path == hook.path &&
2082 entry.signature == hook.signature &&
2083 entry.obj == hook.obj &&
2084 entry.midx == hook.midx &&
2085 entry.argumentMatch == hook.argumentMatch) {
2086 // no need to compare the parameters if it's the same slot
2087 return true; // already there
2091 connectSignal(key, hook);
2095 void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
2097 signalHooks.insertMulti(key, hook);
2098 connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2099 Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
2101 MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
2103 if (it != matchRefCounts.end()) { // Match already present
2104 it.value() = it.value() + 1;
2108 matchRefCounts.insert(hook.matchRule, 1);
2111 if (mode != QDBusConnectionPrivate::PeerMode) {
2112 qDBusDebug("Adding rule: %s", hook.matchRule.constData());
2113 q_dbus_bus_add_match(connection, hook.matchRule, NULL);
2115 // Successfully connected the signal
2116 // Do we need to watch for this name?
2117 if (shouldWatchService(hook.service)) {
2118 WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
2119 if (++data.refcount == 1) {
2120 // we need to watch for this service changing
2121 connectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2122 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2123 this, SLOT(serviceOwnerChangedNoLock(QString,QString,QString)));
2124 data.owner = getNameOwnerNoCache(hook.service);
2125 qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
2126 << data.owner << ")";
2133 bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
2134 const QString &path, const QString &interface, const QString &name,
2135 const QStringList &argumentMatch, const QString &signature,
2136 QObject *receiver, const char *slot)
2139 QDBusConnectionPrivate::SignalHook hook;
2141 QString name2 = name;
2145 hook.signature = signature;
2146 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2147 return false; // don't disconnect
2149 // avoid duplicating:
2150 QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
2151 QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
2152 for ( ; it != end && it.key() == key; ++it) {
2153 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2154 if (entry.service == hook.service &&
2155 entry.path == hook.path &&
2156 entry.signature == hook.signature &&
2157 entry.obj == hook.obj &&
2158 entry.midx == hook.midx &&
2159 entry.argumentMatch == hook.argumentMatch) {
2160 // no need to compare the parameters if it's the same slot
2161 disconnectSignal(it);
2162 return true; // it was there
2166 // the slot was not found
2170 QDBusConnectionPrivate::SignalHookHash::Iterator
2171 QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
2173 const SignalHook &hook = it.value();
2176 MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
2177 if (i == matchRefCounts.end()) {
2178 qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
2180 if (i.value() == 1) {
2182 matchRefCounts.erase(i);
2185 i.value() = i.value() - 1;
2189 // we don't care about errors here
2190 if (connection && erase) {
2191 if (mode != QDBusConnectionPrivate::PeerMode) {
2192 qDBusDebug("Removing rule: %s", hook.matchRule.constData());
2193 q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
2195 // Successfully disconnected the signal
2196 // Were we watching for this name?
2197 WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
2198 if (sit != watchedServices.end()) {
2199 if (--sit.value().refcount == 0) {
2200 watchedServices.erase(sit);
2201 disconnectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2202 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2203 this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
2210 return signalHooks.erase(it);
2213 void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
2215 connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2216 Qt::DirectConnection);
2218 if (node->flags & (QDBusConnection::ExportAdaptors
2219 | QDBusConnection::ExportScriptableSignals
2220 | QDBusConnection::ExportNonScriptableSignals)) {
2221 QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
2223 if (node->flags & (QDBusConnection::ExportScriptableSignals
2224 | QDBusConnection::ExportNonScriptableSignals)) {
2225 connector->disconnectAllSignals(node->obj);
2226 connector->connectAllSignals(node->obj);
2229 // disconnect and reconnect to avoid duplicates
2230 connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2231 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
2232 connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2233 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2234 Qt::DirectConnection);
2238 void QDBusConnectionPrivate::connectRelay(const QString &service,
2239 const QString &path, const QString &interface,
2240 QDBusAbstractInterface *receiver,
2241 const QMetaMethod &signal)
2243 // this function is called by QDBusAbstractInterface when one of its signals is connected
2244 // we set up a relay from D-Bus into it
2249 sig.append(QSIGNAL_CODE + '0');
2250 sig.append(signal.methodSignature());
2251 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, sig,
2252 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2253 return; // don't connect
2255 // add it to our list:
2256 QDBusWriteLocker locker(ConnectRelayAction, this);
2257 SignalHookHash::ConstIterator it = signalHooks.constFind(key);
2258 SignalHookHash::ConstIterator end = signalHooks.constEnd();
2259 for ( ; it != end && it.key() == key; ++it) {
2260 const SignalHook &entry = it.value();
2261 if (entry.service == hook.service &&
2262 entry.path == hook.path &&
2263 entry.signature == hook.signature &&
2264 entry.obj == hook.obj &&
2265 entry.midx == hook.midx)
2266 return; // already there, no need to re-add
2269 connectSignal(key, hook);
2272 void QDBusConnectionPrivate::disconnectRelay(const QString &service,
2273 const QString &path, const QString &interface,
2274 QDBusAbstractInterface *receiver,
2275 const QMetaMethod &signal)
2277 // this function is called by QDBusAbstractInterface when one of its signals is disconnected
2278 // we remove relay from D-Bus into it
2283 sig.append(QSIGNAL_CODE + '0');
2284 sig.append(signal.methodSignature());
2285 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, sig,
2286 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2287 return; // don't connect
2289 // remove it from our list:
2290 QDBusWriteLocker locker(DisconnectRelayAction, this);
2291 SignalHookHash::Iterator it = signalHooks.find(key);
2292 SignalHookHash::Iterator end = signalHooks.end();
2293 for ( ; it != end && it.key() == key; ++it) {
2294 const SignalHook &entry = it.value();
2295 if (entry.service == hook.service &&
2296 entry.path == hook.path &&
2297 entry.signature == hook.signature &&
2298 entry.obj == hook.obj &&
2299 entry.midx == hook.midx) {
2301 disconnectSignal(it);
2306 qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
2309 QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
2311 if (QDBusUtil::isValidUniqueConnectionName(serviceName))
2317 // acquire a read lock for the cache
2318 QReadLocker locker(&lock);
2319 WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
2320 if (it != watchedServices.constEnd())
2325 return getNameOwnerNoCache(serviceName);
2328 QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
2330 QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2331 QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2332 QLatin1String("GetNameOwner"));
2333 QDBusMessagePrivate::setParametersValidated(msg, true);
2335 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2336 if (reply.type() == QDBusMessage::ReplyMessage)
2337 return reply.arguments().at(0).toString();
2342 QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
2343 const QString &interface, QDBusError &error)
2345 // service must be a unique connection name
2346 if (!interface.isEmpty()) {
2347 QDBusReadLocker locker(FindMetaObject1Action, this);
2348 QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
2353 // introspect the target object
2354 QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
2355 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
2356 QLatin1String("Introspect"));
2357 QDBusMessagePrivate::setParametersValidated(msg, true);
2359 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2361 // it doesn't exist yet, we have to create it
2362 QDBusWriteLocker locker(FindMetaObject2Action, this);
2363 QDBusMetaObject *mo = 0;
2364 if (!interface.isEmpty())
2365 mo = cachedMetaObjects.value(interface, 0);
2367 // maybe it got created when we switched from read to write lock
2371 if (reply.type() == QDBusMessage::ReplyMessage) {
2372 if (reply.signature() == QLatin1String("s"))
2373 // fetch the XML description
2374 xml = reply.arguments().at(0).toString();
2376 error = QDBusError(reply);
2378 if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
2382 // release the lock and return
2383 QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
2384 cachedMetaObjects, error);
2389 void QDBusConnectionPrivate::registerService(const QString &serviceName)
2391 QDBusWriteLocker locker(RegisterServiceAction, this);
2392 registerServiceNoLock(serviceName);
2395 void QDBusConnectionPrivate::registerServiceNoLock(const QString &serviceName)
2397 serviceNames.append(serviceName);
2400 void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
2402 QDBusWriteLocker locker(UnregisterServiceAction, this);
2403 unregisterServiceNoLock(serviceName);
2406 void QDBusConnectionPrivate::unregisterServiceNoLock(const QString &serviceName)
2408 serviceNames.removeAll(serviceName);
2411 bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
2413 if (!serviceName.isEmpty() && serviceName == baseService)
2415 QStringList copy = serviceNames;
2416 return copy.contains(serviceName);
2419 void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
2421 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
2422 QCoreApplication::postEvent(object, ev);
2423 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
2428 #endif // QT_NO_DBUS