1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtDBus module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** 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_, QList<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 QByteArray slotname = mm.signature();
644 int paren = slotname.indexOf('(');
645 if (paren != name.length() || !slotname.startsWith(name))
648 int returnType = qDBusNameToTypeId(mm.typeName());
649 bool isAsync = qDBusCheckAsyncTag(mm.tag());
650 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
652 // consistency check:
653 if (isAsync && returnType != QMetaType::Void)
656 int inputCount = qDBusParametersForMethod(mm, metaTypes);
657 if (inputCount == -1)
658 continue; // problem parsing
660 metaTypes[0] = returnType;
661 bool hasMessage = false;
662 if (inputCount > 0 &&
663 metaTypes.at(inputCount) == QDBusMetaTypeId::message) {
664 // "no input parameters" is allowed as long as the message meta type is there
669 // try to match the parameters
671 QByteArray reconstructedSignature;
672 for (i = 1; i <= inputCount; ++i) {
673 const char *typeSignature = QDBusMetaType::typeToSignature( metaTypes.at(i) );
677 reconstructedSignature += typeSignature;
678 if (!msgSignature.startsWith(reconstructedSignature))
682 if (reconstructedSignature != msgSignature)
683 continue; // we didn't match them all
688 // make sure that the output parameters have signatures too
689 if (returnType != 0 && QDBusMetaType::typeToSignature(returnType) == 0)
693 for (int j = i; ok && j < metaTypes.count(); ++j)
694 if (QDBusMetaType::typeToSignature(metaTypes.at(i)) == 0)
699 // consistency check:
700 if (isAsync && metaTypes.count() > i + 1)
703 if (mm.methodType() == QMetaMethod::Slot) {
704 if (isScriptable && (flags & QDBusConnection::ExportScriptableSlots) == 0)
705 continue; // scriptable slots not exported
706 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableSlots) == 0)
707 continue; // non-scriptable slots not exported
709 if (isScriptable && (flags & QDBusConnection::ExportScriptableInvokables) == 0)
710 continue; // scriptable invokables not exported
711 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableInvokables) == 0)
712 continue; // non-scriptable invokables not exported
715 // if we got here, this slot matched
723 static QDBusCallDeliveryEvent * const DIRECT_DELIVERY = (QDBusCallDeliveryEvent *)1;
725 QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
726 QObject *object, int idx,
727 const QList<int> &metaTypes,
728 const QDBusMessage &msg)
733 int n = metaTypes.count() - 1;
734 if (metaTypes[n] == QDBusMetaTypeId::message)
737 if (msg.arguments().count() < n)
738 return 0; // too few arguments
740 // check that types match
741 for (int i = 0; i < n; ++i)
742 if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() &&
743 msg.arguments().at(i).userType() != qMetaTypeId<QDBusArgument>())
744 return 0; // no match
747 // prepare for the call
748 if (target == object)
749 return DIRECT_DELIVERY;
750 return new QDBusCallDeliveryEvent(QDBusConnection(target), idx, target, msg, metaTypes);
753 void QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
754 const QDBusMessage &msg)
756 // This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
757 // that was received from D-Bus
759 // Signals are delivered to slots if the parameters match
760 // Slots can have less parameters than there are on the message
761 // Slots can optionally have one final parameter that is a QDBusMessage
762 // Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
763 QDBusCallDeliveryEvent *call = prepareReply(this, hook.obj, hook.midx, hook.params, msg);
764 if (call == DIRECT_DELIVERY) {
765 // short-circuit delivery
766 Q_ASSERT(this == hook.obj);
767 deliverCall(this, 0, msg, hook.params, hook.midx);
771 postEventToThread(ActivateSignalAction, hook.obj, call);
774 bool QDBusConnectionPrivate::activateCall(QObject* object, int flags, const QDBusMessage &msg)
776 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call
777 // to a slot on the object.
779 // The call is delivered to the first slot that matches the following conditions:
780 // - has the same name as the message's target member
781 // - ALL of the message's types are found in slot's parameter list
782 // - optionally has one more parameter of type QDBusMessage
783 // If none match, then the slot of the same name as the message target and with
784 // the first type of QDBusMessage is delivered.
786 // The D-Bus specification requires that all MethodCall messages be replied to, unless the
787 // caller specifically waived this requirement. This means that we inspect if the user slot
788 // generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
789 // QDBusMessage parameter, it cannot generate a reply.
791 // When a return message is generated, the slot's return type, if any, will be placed
792 // in the message's first position. If there are non-const reference parameters to the
793 // slot, they must appear at the end and will be placed in the subsequent message
796 static const char cachePropertyName[] = "_qdbus_slotCache";
801 #ifndef QT_NO_PROPERTIES
802 Q_ASSERT_X(QThread::currentThread() == object->thread(),
803 "QDBusConnection: internal threading error",
804 "function called for an object that is in another thread!!");
806 QDBusSlotCache slotCache =
807 qvariant_cast<QDBusSlotCache>(object->property(cachePropertyName));
808 QString cacheKey = msg.member(), signature = msg.signature();
809 if (!signature.isEmpty()) {
810 cacheKey.reserve(cacheKey.length() + 1 + signature.length());
811 cacheKey += QLatin1Char('.');
812 cacheKey += signature;
815 QDBusSlotCache::Hash::ConstIterator cacheIt = slotCache.hash.constFind(cacheKey);
816 while (cacheIt != slotCache.hash.constEnd() && cacheIt->flags != flags &&
817 cacheIt.key() == cacheKey)
819 if (cacheIt == slotCache.hash.constEnd() || cacheIt.key() != cacheKey)
821 // not cached, analyze the meta object
822 const QMetaObject *mo = object->metaObject();
823 QByteArray memberName = msg.member().toUtf8();
825 // find a slot that matches according to the rules above
826 QDBusSlotCache::Data slotData;
827 slotData.flags = flags;
828 slotData.slotIdx = ::findSlot(mo, memberName, flags, msg.signature(), slotData.metaTypes);
829 if (slotData.slotIdx == -1) {
830 // ### this is where we want to add the connection as an arg too
831 // try with no parameters, but with a QDBusMessage
832 slotData.slotIdx = ::findSlot(mo, memberName, flags, QString(), slotData.metaTypes);
833 if (slotData.metaTypes.count() != 2 ||
834 slotData.metaTypes.at(1) != QDBusMetaTypeId::message) {
836 // save the negative lookup
837 slotData.slotIdx = -1;
838 slotData.metaTypes.clear();
839 slotCache.hash.insert(cacheKey, slotData);
840 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
846 slotCache.hash.insert(cacheKey, slotData);
847 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
849 // found the slot to be called
850 deliverCall(object, flags, msg, slotData.metaTypes, slotData.slotIdx);
852 } else if (cacheIt->slotIdx == -1) {
857 deliverCall(object, flags, msg, cacheIt->metaTypes, cacheIt->slotIdx);
860 #endif // QT_NO_PROPERTIES
864 void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const QDBusMessage &msg,
865 const QList<int> &metaTypes, int slotIdx)
867 Q_ASSERT_X(!object || QThread::currentThread() == object->thread(),
868 "QDBusConnection: internal threading error",
869 "function called for an object that is in another thread!!");
871 QVarLengthArray<void *, 10> params;
872 params.reserve(metaTypes.count());
874 QVariantList auxParameters;
875 // let's create the parameter list
877 // first one is the return type -- add it below
880 // add the input parameters
882 int pCount = qMin(msg.arguments().count(), metaTypes.count() - 1);
883 for (i = 1; i <= pCount; ++i) {
884 int id = metaTypes[i];
885 if (id == QDBusMetaTypeId::message)
888 const QVariant &arg = msg.arguments().at(i - 1);
889 if (arg.userType() == id)
890 // no conversion needed
891 params.append(const_cast<void *>(arg.constData()));
892 else if (arg.userType() == qMetaTypeId<QDBusArgument>()) {
893 // convert to what the function expects
895 auxParameters.append(QVariant(id, null));
897 const QDBusArgument &in =
898 *reinterpret_cast<const QDBusArgument *>(arg.constData());
899 QVariant &out = auxParameters[auxParameters.count() - 1];
901 if (!QDBusMetaType::demarshall(in, out.userType(), out.data()))
902 qFatal("Internal error: demarshalling function for type '%s' (%d) failed!",
903 out.typeName(), out.userType());
905 params.append(const_cast<void *>(out.constData()));
907 qFatal("Internal error: got invalid meta type %d (%s) "
908 "when trying to convert to meta type %d (%s)",
909 arg.userType(), QMetaType::typeName(arg.userType()),
910 id, QMetaType::typeName(id));
914 bool takesMessage = false;
915 if (metaTypes.count() > i && metaTypes[i] == QDBusMetaTypeId::message) {
916 params.append(const_cast<void*>(static_cast<const void*>(&msg)));
922 QVariantList outputArgs;
924 if (metaTypes[0] != QMetaType::Void) {
925 QVariant arg(metaTypes[0], null);
926 outputArgs.append( arg );
927 params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
929 for ( ; i < metaTypes.count(); ++i) {
930 QVariant arg(metaTypes[i], null);
931 outputArgs.append( arg );
932 params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
940 // FIXME: save the old sender!
941 QDBusContextPrivate context(QDBusConnection(this), msg);
942 QDBusContextPrivate *old = QDBusContextPrivate::set(object, &context);
943 QDBusConnectionPrivate::setSender(this);
945 QPointer<QObject> ptr = object;
946 fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
947 slotIdx, params.data()) >= 0;
948 QDBusConnectionPrivate::setSender(0);
949 // the object might be deleted in the slot
951 QDBusContextPrivate::set(object, old);
954 // do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
956 if (msg.isReplyRequired() && !msg.isDelayedReply()) {
959 qDBusDebug() << this << "Automatically sending reply:" << outputArgs;
960 send(msg.createReply(outputArgs));
962 // generate internal error
963 qWarning("Internal error: Failed to deliver message");
964 send(msg.createErrorReply(QDBusError::InternalError,
965 QLatin1String("Failed to deliver message")));
972 extern bool qDBusInitThreads();
974 QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
975 : QObject(p), ref(1), capabilities(0), mode(InvalidMode), connection(0), server(0), busService(0),
976 watchAndTimeoutLock(QMutex::Recursive),
977 rootNode(QString(QLatin1Char('/')))
979 static const bool threads = q_dbus_threads_init_default();
980 static const int debugging = qgetenv("QDBUS_DEBUG").toInt();
981 ::isDebugging = debugging;
985 #ifdef QDBUS_THREAD_DEBUG
987 qdbusThreadDebug = qdbusDefaultThreadDebug;
990 QDBusMetaTypeId::init();
994 // prepopulate watchedServices:
995 // we know that the owner of org.freedesktop.DBus is itself
996 watchedServices.insert(dbusServiceString(), WatchedServiceData(dbusServiceString(), 1));
998 // prepopulate matchRefCounts:
999 // we know that org.freedesktop.DBus will never change owners
1000 matchRefCounts.insert("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.DBus'", 1);
1003 QDBusConnectionPrivate::~QDBusConnectionPrivate()
1005 if (thread() && thread() != QThread::currentThread())
1006 qWarning("QDBusConnection(name=\"%s\")'s last reference in not in its creation thread! "
1007 "Timer and socket errors will follow and the program will probably crash",
1011 rootNode.children.clear(); // free resources
1012 qDeleteAll(cachedMetaObjects);
1015 q_dbus_server_unref(server);
1017 q_dbus_connection_unref(connection);
1023 void QDBusConnectionPrivate::deleteYourself()
1025 if (thread() && thread() != QThread::currentThread()) {
1026 // last reference dropped while not in the correct thread
1027 // ask the correct thread to delete
1029 // note: since we're posting an event to another thread, we
1030 // must consider deleteLater() to take effect immediately
1037 void QDBusConnectionPrivate::closeConnection()
1039 QDBusWriteLocker locker(CloseConnectionAction, this);
1040 ConnectionMode oldMode = mode;
1041 mode = InvalidMode; // prevent reentrancy
1042 baseService.clear();
1045 q_dbus_server_disconnect(server);
1047 if (oldMode == ClientMode || oldMode == PeerMode) {
1049 q_dbus_connection_close(connection);
1050 // send the "close" message
1051 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS)
1057 void QDBusConnectionPrivate::checkThread()
1060 if (QCoreApplication::instance())
1061 moveToThread(QCoreApplication::instance()->thread());
1063 qWarning("The thread that had QDBusConnection('%s') has died and there is no main thread",
1068 bool QDBusConnectionPrivate::handleError(const QDBusErrorInternal &error)
1071 return false; // no error
1073 //lock.lockForWrite();
1079 void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
1082 QDBusWatchAndTimeoutLocker locker(TimerEventAction, this);
1083 DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
1085 q_dbus_timeout_handle(timeout);
1091 void QDBusConnectionPrivate::customEvent(QEvent *e)
1093 Q_ASSERT(e->type() == QEvent::User);
1095 QDBusConnectionCallbackEvent *ev = static_cast<QDBusConnectionCallbackEvent *>(e);
1096 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1097 QDBusLockerBase::BeforeDeliver, this);
1098 switch (ev->subtype)
1100 case QDBusConnectionCallbackEvent::AddTimeout: {
1101 QDBusWatchAndTimeoutLocker locker(RealAddTimeoutAction, this);
1102 while (!timeoutsPendingAdd.isEmpty()) {
1103 QPair<DBusTimeout *, int> entry = timeoutsPendingAdd.takeFirst();
1104 qDBusRealAddTimeout(this, entry.first, entry.second);
1109 case QDBusConnectionCallbackEvent::KillTimer:
1110 killTimer(ev->timerId);
1113 case QDBusConnectionCallbackEvent::AddWatch:
1114 qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
1117 case QDBusConnectionCallbackEvent::ToggleWatch:
1118 qDBusRealToggleWatch(this, ev->watch, ev->fd);
1121 QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1122 QDBusLockerBase::AfterDeliver, this);
1125 void QDBusConnectionPrivate::doDispatch()
1127 QDBusDispatchLocker locker(DoDispatchAction, this);
1128 if (mode == ClientMode || mode == PeerMode)
1129 while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
1132 void QDBusConnectionPrivate::socketRead(int fd)
1134 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1137 QDBusWatchAndTimeoutLocker locker(SocketReadAction, this);
1138 WatcherHash::ConstIterator it = watchers.constFind(fd);
1139 while (it != watchers.constEnd() && it.key() == fd) {
1140 if (it->watch && it->read && it->read->isEnabled())
1141 pendingWatches.append(it.value().watch);
1146 for (int i = 0; i < pendingWatches.size(); ++i)
1147 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_READABLE))
1148 qDebug("OUT OF MEM");
1152 void QDBusConnectionPrivate::socketWrite(int fd)
1154 QVarLengthArray<DBusWatch *, 2> pendingWatches;
1157 QDBusWatchAndTimeoutLocker locker(SocketWriteAction, this);
1158 WatcherHash::ConstIterator it = watchers.constFind(fd);
1159 while (it != watchers.constEnd() && it.key() == fd) {
1160 if (it->watch && it->write && it->write->isEnabled())
1161 pendingWatches.append(it.value().watch);
1166 for (int i = 0; i < pendingWatches.size(); ++i)
1167 if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_WRITABLE))
1168 qDebug("OUT OF MEM");
1171 void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
1173 QDBusWriteLocker locker(ObjectDestroyedAction, this);
1174 huntAndDestroy(obj, rootNode);
1176 SignalHookHash::iterator sit = signalHooks.begin();
1177 while (sit != signalHooks.end()) {
1178 if (static_cast<QObject *>(sit.value().obj) == obj)
1179 sit = disconnectSignal(sit);
1184 obj->disconnect(this);
1187 void QDBusConnectionPrivate::relaySignal(QObject *obj, const QMetaObject *mo, int signalId,
1188 const QVariantList &args)
1190 QString interface = qDBusInterfaceFromMetaObject(mo);
1192 QMetaMethod mm = mo->method(signalId);
1193 QByteArray memberName = mm.signature();
1194 memberName.truncate(memberName.indexOf('('));
1196 // check if it's scriptable
1197 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
1198 bool isAdaptor = false;
1199 for ( ; mo; mo = mo->superClass())
1200 if (mo == &QDBusAbstractAdaptor::staticMetaObject) {
1205 QDBusReadLocker locker(RelaySignalAction, this);
1206 QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/"), interface,
1207 QLatin1String(memberName));
1208 QDBusMessagePrivate::setParametersValidated(message, true);
1209 message.setArguments(args);
1211 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1213 qWarning("QDBusConnection: Could not emit signal %s.%s: %s", qPrintable(interface), memberName.constData(),
1214 qPrintable(error.message()));
1219 //qDBusDebug() << "Emitting signal" << message;
1220 //qDBusDebug() << "for paths:";
1221 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1222 huntAndEmit(connection, msg, obj, rootNode, isScriptable, isAdaptor);
1223 q_dbus_message_unref(msg);
1226 void QDBusConnectionPrivate::serviceOwnerChangedNoLock(const QString &name,
1227 const QString &oldOwner, const QString &newOwner)
1230 // QDBusWriteLocker locker(UpdateSignalHookOwnerAction, this);
1231 WatchedServicesHash::Iterator it = watchedServices.find(name);
1232 if (it == watchedServices.end())
1234 if (oldOwner != it->owner)
1235 qWarning("QDBusConnection: name '%s' had owner '%s' but we thought it was '%s'",
1236 qPrintable(name), qPrintable(oldOwner), qPrintable(it->owner));
1238 qDBusDebug() << this << "Updating name" << name << "from" << oldOwner << "to" << newOwner;
1239 it->owner = newOwner;
1242 int QDBusConnectionPrivate::findSlot(QObject* obj, const QByteArray &normalizedName,
1245 int midx = obj->metaObject()->indexOfMethod(normalizedName);
1249 int inputCount = qDBusParametersForMethod(obj->metaObject()->method(midx), params);
1250 if ( inputCount == -1 || inputCount + 1 != params.count() )
1251 return -1; // failed to parse or invalid arguments or output arguments
1256 bool QDBusConnectionPrivate::prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
1257 const QString &service,
1258 const QString &path, const QString &interface, const QString &name,
1259 const QStringList &argMatch,
1260 QObject *receiver, const char *signal, int minMIdx,
1261 bool buildSignature)
1263 QByteArray normalizedName = signal + 1;
1264 hook.midx = findSlot(receiver, signal + 1, hook.params);
1265 if (hook.midx == -1) {
1266 normalizedName = QMetaObject::normalizedSignature(signal + 1);
1267 hook.midx = findSlot(receiver, normalizedName, hook.params);
1269 if (hook.midx < minMIdx) {
1270 if (hook.midx == -1)
1275 hook.service = service;
1277 hook.obj = receiver;
1278 hook.argumentMatch = argMatch;
1280 // build the D-Bus signal name and signature
1281 // This should not happen for QDBusConnection::connect, use buildSignature here, since
1282 // QDBusConnection::connect passes false and everything else uses true
1283 QString mname = name;
1284 if (buildSignature && mname.isNull()) {
1285 normalizedName.truncate(normalizedName.indexOf('('));
1286 mname = QString::fromUtf8(normalizedName);
1289 key.reserve(interface.length() + 1 + mname.length());
1290 key += QLatin1Char(':');
1293 if (buildSignature) {
1294 hook.signature.clear();
1295 for (int i = 1; i < hook.params.count(); ++i)
1296 if (hook.params.at(i) != QDBusMetaTypeId::message)
1297 hook.signature += QLatin1String( QDBusMetaType::typeToSignature( hook.params.at(i) ) );
1300 hook.matchRule = buildMatchRule(service, path, interface, mname, argMatch, hook.signature);
1301 return true; // connect to this signal
1304 void QDBusConnectionPrivate::sendError(const QDBusMessage &msg, QDBusError::ErrorType code)
1306 if (code == QDBusError::UnknownMethod) {
1307 QString interfaceMsg;
1308 if (msg.interface().isEmpty())
1309 interfaceMsg = QLatin1String("any interface");
1311 interfaceMsg = QString::fromLatin1("interface '%1'").arg(msg.interface());
1313 send(msg.createErrorReply(code,
1314 QString::fromLatin1("No such method '%1' in %2 at object path '%3' "
1316 .arg(msg.member(), interfaceMsg, msg.path(), msg.signature())));
1317 } else if (code == QDBusError::UnknownInterface) {
1318 send(msg.createErrorReply(QDBusError::UnknownInterface,
1319 QString::fromLatin1("No such interface '%1' at object path '%2'")
1320 .arg(msg.interface(), msg.path())));
1321 } else if (code == QDBusError::UnknownObject) {
1322 send(msg.createErrorReply(QDBusError::UnknownObject,
1323 QString::fromLatin1("No such object path '%1'").arg(msg.path())));
1327 bool QDBusConnectionPrivate::activateInternalFilters(const ObjectTreeNode &node,
1328 const QDBusMessage &msg)
1330 // object may be null
1331 const QString interface = msg.interface();
1333 if (interface.isEmpty() || interface == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE)) {
1334 if (msg.member() == QLatin1String("Introspect") && msg.signature().isEmpty()) {
1335 //qDebug() << "QDBusConnectionPrivate::activateInternalFilters introspect" << msg.d_ptr->msg;
1336 QDBusMessage reply = msg.createReply(qDBusIntrospectObject(node, msg.path()));
1341 if (!interface.isEmpty()) {
1342 sendError(msg, QDBusError::UnknownMethod);
1347 if (node.obj && (interface.isEmpty() ||
1348 interface == QLatin1String(DBUS_INTERFACE_PROPERTIES))) {
1349 //qDebug() << "QDBusConnectionPrivate::activateInternalFilters properties" << msg.d_ptr->msg;
1350 if (msg.member() == QLatin1String("Get") && msg.signature() == QLatin1String("ss")) {
1351 QDBusMessage reply = qDBusPropertyGet(node, msg);
1354 } else if (msg.member() == QLatin1String("Set") && msg.signature() == QLatin1String("ssv")) {
1355 QDBusMessage reply = qDBusPropertySet(node, msg);
1358 } else if (msg.member() == QLatin1String("GetAll") && msg.signature() == QLatin1String("s")) {
1359 QDBusMessage reply = qDBusPropertyGetAll(node, msg);
1364 if (!interface.isEmpty()) {
1365 sendError(msg, QDBusError::UnknownMethod);
1373 void QDBusConnectionPrivate::activateObject(ObjectTreeNode &node, const QDBusMessage &msg,
1376 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call to a slot
1379 // The call is routed through the adaptor sub-objects if we have any
1381 // object may be null
1383 if (node.flags & QDBusConnectionPrivate::VirtualObject) {
1384 if (node.treeNode->handleMessage(msg, q(this))) {
1387 if (activateInternalFilters(node, msg))
1392 if (pathStartPos != msg.path().length()) {
1393 node.flags &= ~QDBusConnection::ExportAllSignals;
1394 node.obj = findChildObject(&node, msg.path(), pathStartPos);
1396 sendError(msg, QDBusError::UnknownObject);
1401 QDBusAdaptorConnector *connector;
1402 if (node.flags & QDBusConnection::ExportAdaptors &&
1403 (connector = qDBusFindAdaptorConnector(node.obj))) {
1404 int newflags = node.flags | QDBusConnection::ExportAllSlots;
1406 if (msg.interface().isEmpty()) {
1407 // place the call in all interfaces
1408 // let the first one that handles it to work
1409 QDBusAdaptorConnector::AdaptorMap::ConstIterator it =
1410 connector->adaptors.constBegin();
1411 QDBusAdaptorConnector::AdaptorMap::ConstIterator end =
1412 connector->adaptors.constEnd();
1414 for ( ; it != end; ++it)
1415 if (activateCall(it->adaptor, newflags, msg))
1418 // check if we have an interface matching the name that was asked:
1419 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
1420 it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
1422 if (it != connector->adaptors.constEnd() && msg.interface() == QLatin1String(it->interface)) {
1423 if (!activateCall(it->adaptor, newflags, msg))
1424 sendError(msg, QDBusError::UnknownMethod);
1430 // no adaptors matched or were exported
1431 // try our standard filters
1432 if (activateInternalFilters(node, msg))
1433 return; // internal filters have already run or an error has been sent
1435 // try the object itself:
1436 if (node.flags & (QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportNonScriptableSlots) ||
1437 node.flags & (QDBusConnection::ExportScriptableInvokables|QDBusConnection::ExportNonScriptableInvokables)) {
1438 bool interfaceFound = true;
1439 if (!msg.interface().isEmpty())
1440 interfaceFound = qDBusInterfaceInObject(node.obj, msg.interface());
1442 if (interfaceFound) {
1443 if (!activateCall(node.obj, node.flags, msg))
1444 sendError(msg, QDBusError::UnknownMethod);
1449 // nothing matched, send an error code
1450 if (msg.interface().isEmpty())
1451 sendError(msg, QDBusError::UnknownMethod);
1453 sendError(msg, QDBusError::UnknownInterface);
1456 void QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
1458 // if the msg is external, we were called from inside doDispatch
1459 // that means the dispatchLock mutex is locked
1460 // must not call out to user code in that case
1462 // however, if the message is internal, handleMessage was called
1463 // directly and no lock is in place. We can therefore call out to
1464 // user code, if necessary
1465 ObjectTreeNode result;
1467 QThread *objThread = 0;
1472 QDBusReadLocker locker(HandleObjectCallAction, this);
1473 if (!findObject(&rootNode, msg.path(), usedLength, result)) {
1474 // qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
1475 sendError(msg, QDBusError::UnknownObject);
1480 // no object -> no threading issues
1481 // it's either going to be an error, or an internal filter
1482 activateObject(result, msg, usedLength);
1486 objThread = result.obj->thread();
1488 send(msg.createErrorReply(QDBusError::InternalError,
1489 QString::fromLatin1("Object '%1' (at path '%2')"
1490 " has no thread. Cannot deliver message.")
1491 .arg(result.obj->objectName(), msg.path())));
1495 if (!QDBusMessagePrivate::isLocal(msg)) {
1496 // external incoming message
1497 // post it and forget
1498 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1499 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1502 } else if (objThread != QThread::currentThread()) {
1503 // synchronize with other thread
1504 postEventToThread(HandleObjectCallPostEventAction, result.obj,
1505 new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1506 usedLength, msg, &sem));
1511 } // release the lock
1514 SEM_ACQUIRE(HandleObjectCallSemaphoreAction, sem);
1516 activateObject(result, msg, usedLength);
1519 QDBusActivateObjectEvent::~QDBusActivateObjectEvent()
1522 // we're being destroyed without delivering
1523 // it means the object was deleted between posting and delivering
1524 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1525 that->sendError(message, QDBusError::UnknownObject);
1528 // semaphore releasing happens in ~QMetaCallEvent
1531 void QDBusActivateObjectEvent::placeMetaCall(QObject *)
1533 QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1535 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1536 QDBusLockerBase::BeforeDeliver, that);
1537 that->activateObject(node, message, pathStartPos);
1538 QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1539 QDBusLockerBase::AfterDeliver, that);
1544 void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1546 SignalHookHash::const_iterator it = signalHooks.find(key);
1547 SignalHookHash::const_iterator end = signalHooks.constEnd();
1548 //qDebug("looking for: %s", path.toLocal8Bit().constData());
1549 //qDBusDebug() << signalHooks.keys();
1550 for ( ; it != end && it.key() == key; ++it) {
1551 const SignalHook &hook = it.value();
1552 if (!hook.service.isEmpty()) {
1553 const QString owner =
1554 shouldWatchService(hook.service) ?
1555 watchedServices.value(hook.service).owner :
1557 if (owner != msg.service())
1560 if (!hook.path.isEmpty() && hook.path != msg.path())
1562 if (!hook.signature.isEmpty() && hook.signature != msg.signature())
1564 if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1566 if (!hook.argumentMatch.isEmpty()) {
1567 const QVariantList arguments = msg.arguments();
1568 if (hook.argumentMatch.size() > arguments.size())
1571 bool matched = true;
1572 for (int i = 0; i < hook.argumentMatch.size(); ++i) {
1573 const QString ¶m = hook.argumentMatch.at(i);
1575 continue; // don't try to match against this
1576 if (param == arguments.at(i).toString())
1577 continue; // matched
1585 activateSignal(hook, msg);
1589 void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1591 // We call handlesignal(QString, QDBusMessage) three times:
1592 // one with member:interface
1594 // one with :interface
1595 // This allows us to match signals with wildcards on member or interface
1598 QString key = msg.member();
1599 key.reserve(key.length() + 1 + msg.interface().length());
1600 key += QLatin1Char(':');
1601 key += msg.interface();
1603 QDBusReadLocker locker(HandleSignalAction, this);
1604 handleSignal(key, msg); // one try
1606 key.truncate(msg.member().length() + 1); // keep the ':'
1607 handleSignal(key, msg); // second try
1609 key = QLatin1Char(':');
1610 key += msg.interface();
1611 handleSignal(key, msg); // third try
1614 static dbus_int32_t server_slot = -1;
1616 void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
1626 dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
1627 if (data_allocated && server_slot < 0)
1630 dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
1635 //qDebug() << "watch_functions_set" << watch_functions_set;
1636 Q_UNUSED(watch_functions_set);
1638 dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
1643 //qDebug() << "time_functions_set" << time_functions_set;
1644 Q_UNUSED(time_functions_set);
1646 q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1648 dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
1649 //qDebug() << "data_set" << data_set;
1653 void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
1663 q_dbus_connection_set_exit_on_disconnect(connection, false);
1664 q_dbus_connection_set_watch_functions(connection,
1669 q_dbus_connection_set_timeout_functions(connection,
1674 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1675 q_dbus_connection_add_filter(connection,
1679 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1682 static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnection *connection)
1684 QDBusConnection::ConnectionCapabilities result = 0;
1686 #if defined(QT_LINKED_LIBDBUS) && DBUS_VERSION < 0x010400
1687 // no capabilities are possible
1689 # if !defined(QT_LINKED_LIBDBUS)
1690 // run-time check if the next functions are available
1691 int major, minor, micro;
1692 q_dbus_get_version(&major, &minor, µ);
1693 if (major == 1 && minor < 4)
1697 #ifndef DBUS_TYPE_UNIX_FD
1698 # define DBUS_TYPE_UNIX_FD int('h')
1700 if (q_dbus_connection_can_send_type(connection, DBUS_TYPE_UNIX_FD))
1701 result |= QDBusConnection::UnixFileDescriptorPassing;
1707 void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
1717 const char *service = q_dbus_bus_get_unique_name(connection);
1719 baseService = QString::fromUtf8(service);
1720 capabilities = connectionCapabilies(connection);
1722 q_dbus_connection_set_exit_on_disconnect(connection, false);
1723 q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1724 qDBusToggleWatch, this, 0);
1725 q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1726 qDBusToggleTimeout, this, 0);
1727 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1728 q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1730 // Initialize the hooks for the NameAcquired and NameLost signals
1731 // we don't use connectSignal here because we don't need the rules to be sent to the bus
1732 // the bus will always send us these two signals
1734 hook.service = dbusServiceString();
1735 hook.path.clear(); // no matching
1737 hook.params << QMetaType::Void << QVariant::String; // both functions take a QString as parameter and return void
1739 hook.midx = staticMetaObject.indexOfSlot("registerServiceNoLock(QString)");
1740 Q_ASSERT(hook.midx != -1);
1741 signalHooks.insert(QLatin1String("NameAcquired:" DBUS_INTERFACE_DBUS), hook);
1743 hook.midx = staticMetaObject.indexOfSlot("unregisterServiceNoLock(QString)");
1744 Q_ASSERT(hook.midx != -1);
1745 signalHooks.insert(QLatin1String("NameLost:" DBUS_INTERFACE_DBUS), hook);
1747 qDBusDebug() << this << ": connected successfully";
1749 // schedule a dispatch:
1750 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1754 static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1756 QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
1757 Q_ASSERT(call->pending == pending);
1759 QDBusConnectionPrivate::processFinishedCall(call);
1763 void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
1765 Q_ASSERT(pcall->pending);
1766 Q_ASSERT(!pcall->autoDelete);
1767 //Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
1769 if (pcall->waitingForFinished) {
1770 // another thread is already waiting
1771 pcall->waitForFinishedCondition.wait(&pcall->mutex);
1773 pcall->waitingForFinished = true;
1774 pcall->mutex.unlock();
1777 QDBusDispatchLocker locker(PendingCallBlockAction, this);
1778 q_dbus_pending_call_block(pcall->pending);
1779 // QDBusConnectionPrivate::processFinishedCall() is called automatically
1781 pcall->mutex.lock();
1785 void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
1787 QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1789 QMutexLocker locker(&call->mutex);
1791 QDBusMessage &msg = call->replyMessage;
1792 if (call->pending) {
1793 // decode the message
1794 DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
1795 msg = QDBusMessagePrivate::fromDBusMessage(reply, connection->capabilities);
1796 q_dbus_message_unref(reply);
1798 qDBusDebug() << connection << "got message reply (async):" << msg;
1800 // Check if the reply has the expected signature
1801 call->checkReceivedSignature();
1803 if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
1804 // Deliver the return values of a remote function call.
1806 // There is only one connection and it is specified by idx
1807 // The slot must have the same parameter types that the message does
1808 // The slot may have less parameters than the message
1809 // The slot may optionally have one final parameter that is QDBusMessage
1810 // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1812 QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
1813 call->metaTypes, msg);
1815 connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
1817 qDBusDebug() << "Deliver failed!";
1821 q_dbus_pending_call_unref(call->pending);
1826 // Are there any watchers?
1827 if (call->watcherHelper)
1828 call->watcherHelper->emitSignals(msg, call->sentMessage);
1830 if (msg.type() == QDBusMessage::ErrorMessage)
1831 emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
1833 if (call->autoDelete) {
1834 Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
1839 int QDBusConnectionPrivate::send(const QDBusMessage& message)
1841 if (QDBusMessagePrivate::isLocal(message))
1842 return -1; // don't send; the reply will be retrieved by the caller
1843 // through the d_ptr->localReply link
1846 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1848 if (message.type() == QDBusMessage::MethodCallMessage)
1849 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1850 qPrintable(message.service()), qPrintable(message.path()),
1851 qPrintable(message.interface()), qPrintable(message.member()),
1852 qPrintable(error.message()));
1853 else if (message.type() == QDBusMessage::SignalMessage)
1854 qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
1855 qPrintable(message.path()), qPrintable(message.interface()),
1856 qPrintable(message.member()),
1857 qPrintable(error.message()));
1859 qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
1860 message.type() == QDBusMessage::ReplyMessage ? "reply" :
1861 message.type() == QDBusMessage::ErrorMessage ? "error" :
1862 "invalid", qPrintable(message.service()),
1863 qPrintable(error.message()));
1868 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1870 qDBusDebug() << this << "sending message (no reply):" << message;
1872 bool isOk = q_dbus_connection_send(connection, msg, 0);
1875 serial = q_dbus_message_get_serial(msg);
1877 q_dbus_message_unref(msg);
1881 QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1882 int sendMode, int timeout)
1885 if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
1886 && isServiceRegisteredByThread(message.service()))
1887 // special case for synchronous local calls
1888 return sendWithReplyLocal(message);
1890 if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
1892 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &err);
1894 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1895 qPrintable(message.service()), qPrintable(message.path()),
1896 qPrintable(message.interface()), qPrintable(message.member()),
1897 qPrintable(err.message()));
1899 return QDBusMessage::createError(err);
1902 qDBusDebug() << this << "sending message (blocking):" << message;
1903 QDBusErrorInternal error;
1904 DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
1906 q_dbus_message_unref(msg);
1909 lastError = err = error;
1910 return QDBusMessage::createError(err);
1913 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply, capabilities);
1914 q_dbus_message_unref(reply);
1915 qDBusDebug() << this << "got message reply (blocking):" << amsg;
1918 } else { // use the event loop
1919 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1922 if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
1923 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
1925 loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
1926 loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
1928 // enter the event loop and wait for a reply
1929 loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1932 QDBusMessage reply = pcall->replyMessage;
1933 lastError = reply; // set or clear error
1940 QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
1942 qDBusDebug() << this << "sending message via local-loop:" << message;
1944 QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
1945 bool handled = handleMessage(localCallMsg);
1948 QString interface = message.interface();
1949 if (interface.isEmpty())
1950 interface = QLatin1String("<no-interface>");
1951 return QDBusMessage::createError(QDBusError::InternalError,
1952 QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
1953 .arg(interface, message.member(),
1954 message.path(), message.signature()));
1957 // if the message was handled, there might be a reply
1958 QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
1959 if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
1960 qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
1961 "on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
1962 qPrintable(message.signature()));
1963 return QDBusMessage::createError(
1964 QDBusError(QDBusError::InternalError,
1965 QLatin1String("local-loop message cannot have delayed replies")));
1969 qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
1970 return localReplyMsg;
1973 QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
1976 if (isServiceRegisteredByThread(message.service())) {
1977 // special case for local calls
1978 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1979 pcall->replyMessage = sendWithReplyLocal(message);
1985 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1989 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1991 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1992 qPrintable(message.service()), qPrintable(message.path()),
1993 qPrintable(message.interface()), qPrintable(message.member()),
1994 qPrintable(error.message()));
1995 pcall->replyMessage = QDBusMessage::createError(error);
2000 qDBusDebug() << this << "sending message (async):" << message;
2001 DBusPendingCall *pending = 0;
2003 QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
2004 if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
2006 q_dbus_message_unref(msg);
2008 pcall->pending = pending;
2009 q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
2013 // we're probably disconnected at this point
2014 lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
2017 lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
2020 q_dbus_message_unref(msg);
2021 pcall->replyMessage = QDBusMessage::createError(error);
2025 int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
2026 const char *returnMethod, const char *errorMethod,
2029 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
2032 // has it already finished with success (dispatched locally)?
2033 if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
2034 pcall->setReplyCallback(receiver, returnMethod);
2035 processFinishedCall(pcall);
2040 // either it hasn't finished or it has finished with error
2042 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
2043 connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
2044 Qt::QueuedConnection);
2045 pcall->watcherHelper->moveToThread(thread());
2048 // has it already finished and is an error reply message?
2049 if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
2050 processFinishedCall(pcall);
2055 pcall->autoDelete = true;
2057 pcall->setReplyCallback(receiver, returnMethod);
2062 bool QDBusConnectionPrivate::connectSignal(const QString &service,
2063 const QString &path, const QString &interface, const QString &name,
2064 const QStringList &argumentMatch, const QString &signature,
2065 QObject *receiver, const char *slot)
2068 QDBusConnectionPrivate::SignalHook hook;
2070 QString name2 = name;
2074 hook.signature = signature;
2075 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2076 return false; // don't connect
2078 // avoid duplicating:
2079 QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.find(key);
2080 QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
2081 for ( ; it != end && it.key() == key; ++it) {
2082 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2083 if (entry.service == hook.service &&
2084 entry.path == hook.path &&
2085 entry.signature == hook.signature &&
2086 entry.obj == hook.obj &&
2087 entry.midx == hook.midx &&
2088 entry.argumentMatch == hook.argumentMatch) {
2089 // no need to compare the parameters if it's the same slot
2090 return true; // already there
2094 connectSignal(key, hook);
2098 void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
2100 signalHooks.insertMulti(key, hook);
2101 connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2102 Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
2104 MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
2106 if (it != matchRefCounts.end()) { // Match already present
2107 it.value() = it.value() + 1;
2111 matchRefCounts.insert(hook.matchRule, 1);
2114 if (mode != QDBusConnectionPrivate::PeerMode) {
2115 qDBusDebug("Adding rule: %s", hook.matchRule.constData());
2116 q_dbus_bus_add_match(connection, hook.matchRule, NULL);
2118 // Successfully connected the signal
2119 // Do we need to watch for this name?
2120 if (shouldWatchService(hook.service)) {
2121 WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
2122 if (++data.refcount == 1) {
2123 // we need to watch for this service changing
2124 connectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2125 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2126 this, SLOT(serviceOwnerChangedNoLock(QString,QString,QString)));
2127 data.owner = getNameOwnerNoCache(hook.service);
2128 qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
2129 << data.owner << ")";
2136 bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
2137 const QString &path, const QString &interface, const QString &name,
2138 const QStringList &argumentMatch, const QString &signature,
2139 QObject *receiver, const char *slot)
2142 QDBusConnectionPrivate::SignalHook hook;
2144 QString name2 = name;
2148 hook.signature = signature;
2149 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2150 return false; // don't disconnect
2152 // avoid duplicating:
2153 QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
2154 QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
2155 for ( ; it != end && it.key() == key; ++it) {
2156 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2157 if (entry.service == hook.service &&
2158 entry.path == hook.path &&
2159 entry.signature == hook.signature &&
2160 entry.obj == hook.obj &&
2161 entry.midx == hook.midx &&
2162 entry.argumentMatch == hook.argumentMatch) {
2163 // no need to compare the parameters if it's the same slot
2164 disconnectSignal(it);
2165 return true; // it was there
2169 // the slot was not found
2173 QDBusConnectionPrivate::SignalHookHash::Iterator
2174 QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
2176 const SignalHook &hook = it.value();
2179 MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
2180 if (i == matchRefCounts.end()) {
2181 qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
2183 if (i.value() == 1) {
2185 matchRefCounts.erase(i);
2188 i.value() = i.value() - 1;
2192 // we don't care about errors here
2193 if (connection && erase) {
2194 if (mode != QDBusConnectionPrivate::PeerMode) {
2195 qDBusDebug("Removing rule: %s", hook.matchRule.constData());
2196 q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
2198 // Successfully disconnected the signal
2199 // Were we watching for this name?
2200 WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
2201 if (sit != watchedServices.end()) {
2202 if (--sit.value().refcount == 0) {
2203 watchedServices.erase(sit);
2204 disconnectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2205 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2206 this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
2213 return signalHooks.erase(it);
2216 void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
2218 connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2219 Qt::DirectConnection);
2221 if (node->flags & (QDBusConnection::ExportAdaptors
2222 | QDBusConnection::ExportScriptableSignals
2223 | QDBusConnection::ExportNonScriptableSignals)) {
2224 QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
2226 if (node->flags & (QDBusConnection::ExportScriptableSignals
2227 | QDBusConnection::ExportNonScriptableSignals)) {
2228 connector->disconnectAllSignals(node->obj);
2229 connector->connectAllSignals(node->obj);
2232 // disconnect and reconnect to avoid duplicates
2233 connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2234 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
2235 connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2236 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2237 Qt::DirectConnection);
2241 void QDBusConnectionPrivate::connectRelay(const QString &service,
2242 const QString &path, const QString &interface,
2243 QDBusAbstractInterface *receiver,
2246 // this function is called by QDBusAbstractInterface when one of its signals is connected
2247 // we set up a relay from D-Bus into it
2251 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
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.find(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,
2277 // this function is called by QDBusAbstractInterface when one of its signals is disconnected
2278 // we remove relay from D-Bus into it
2282 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
2283 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2284 return; // don't connect
2286 // remove it from our list:
2287 QDBusWriteLocker locker(DisconnectRelayAction, this);
2288 SignalHookHash::Iterator it = signalHooks.find(key);
2289 SignalHookHash::Iterator end = signalHooks.end();
2290 for ( ; it != end && it.key() == key; ++it) {
2291 const SignalHook &entry = it.value();
2292 if (entry.service == hook.service &&
2293 entry.path == hook.path &&
2294 entry.signature == hook.signature &&
2295 entry.obj == hook.obj &&
2296 entry.midx == hook.midx) {
2298 disconnectSignal(it);
2303 qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
2306 QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
2308 if (QDBusUtil::isValidUniqueConnectionName(serviceName))
2314 // acquire a read lock for the cache
2315 QReadLocker locker(&lock);
2316 WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
2317 if (it != watchedServices.constEnd())
2322 return getNameOwnerNoCache(serviceName);
2325 QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
2327 QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2328 QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2329 QLatin1String("GetNameOwner"));
2330 QDBusMessagePrivate::setParametersValidated(msg, true);
2332 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2333 if (reply.type() == QDBusMessage::ReplyMessage)
2334 return reply.arguments().at(0).toString();
2339 QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
2340 const QString &interface, QDBusError &error)
2342 // service must be a unique connection name
2343 if (!interface.isEmpty()) {
2344 QDBusReadLocker locker(FindMetaObject1Action, this);
2345 QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
2350 // introspect the target object
2351 QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
2352 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
2353 QLatin1String("Introspect"));
2354 QDBusMessagePrivate::setParametersValidated(msg, true);
2356 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2358 // it doesn't exist yet, we have to create it
2359 QDBusWriteLocker locker(FindMetaObject2Action, this);
2360 QDBusMetaObject *mo = 0;
2361 if (!interface.isEmpty())
2362 mo = cachedMetaObjects.value(interface, 0);
2364 // maybe it got created when we switched from read to write lock
2368 if (reply.type() == QDBusMessage::ReplyMessage) {
2369 if (reply.signature() == QLatin1String("s"))
2370 // fetch the XML description
2371 xml = reply.arguments().at(0).toString();
2375 if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
2379 // release the lock and return
2380 QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
2381 cachedMetaObjects, error);
2386 void QDBusConnectionPrivate::registerService(const QString &serviceName)
2388 QDBusWriteLocker locker(RegisterServiceAction, this);
2389 registerServiceNoLock(serviceName);
2392 void QDBusConnectionPrivate::registerServiceNoLock(const QString &serviceName)
2394 serviceNames.append(serviceName);
2397 void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
2399 QDBusWriteLocker locker(UnregisterServiceAction, this);
2400 unregisterServiceNoLock(serviceName);
2403 void QDBusConnectionPrivate::unregisterServiceNoLock(const QString &serviceName)
2405 serviceNames.removeAll(serviceName);
2408 bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
2410 if (!serviceName.isEmpty() && serviceName == baseService)
2412 QStringList copy = serviceNames;
2413 return copy.contains(serviceName);
2416 void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
2418 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
2419 QCoreApplication::postEvent(object, ev);
2420 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
2425 #endif // QT_NO_DBUS