1 /* qdbusintegrator.cpp QDBusConnection private implementation
3 * Copyright (C) 2005 Harald Fernengel <harry@kdevelop.org>
4 * Copyright (C) 2006 Trolltech AS. All rights reserved.
5 * Author: Thiago Macieira <thiago.macieira@trolltech.com>
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software Foundation
21 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include <qcoreapplication.h>
26 #include <qcoreevent.h>
28 #include <qmetaobject.h>
30 #include <qsocketnotifier.h>
31 #include <qstringlist.h>
34 #include "qdbusconnection_p.h"
35 #include "qdbusinterface_p.h"
36 #include "qdbusmessage.h"
37 #include "qdbusabstractadaptor.h"
38 #include "qdbusabstractadaptor_p.h"
39 #include "qdbustypehelper_p.h"
40 #include "qdbusutil.h"
41 #include "qdbustype_p.h"
43 #ifndef USE_OUTSIDE_DISPATCH
44 # define USE_OUTSIDE_DISPATCH 0
47 int QDBusConnectionPrivate::messageMetaType = 0;
49 typedef void (*qDBusSpyHook)(const QDBusMessage&);
50 static qDBusSpyHook messageSpyHook;
52 struct QDBusPendingCall
54 QPointer<QObject> receiver;
57 DBusPendingCall *pending;
58 const QDBusConnectionPrivate *connection;
61 class CallDeliveryEvent: public QEvent
65 : QEvent(QEvent::User), object(0), flags(0), slotIdx(-1)
68 const QDBusConnectionPrivate *conn;
69 QPointer<QObject> object;
77 static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
82 // qDebug("addTimeout %d", dbus_timeout_get_interval(timeout));
84 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
86 if (!dbus_timeout_get_enabled(timeout))
89 if (!QCoreApplication::instance()) {
90 d->pendingTimeouts.append(timeout);
93 int timerId = d->startTimer(dbus_timeout_get_interval(timeout));
97 d->timeouts[timerId] = timeout;
101 static void qDBusRemoveTimeout(DBusTimeout *timeout, void *data)
106 // qDebug("removeTimeout");
108 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
109 d->pendingTimeouts.removeAll(timeout);
111 QDBusConnectionPrivate::TimeoutHash::iterator it = d->timeouts.begin();
112 while (it != d->timeouts.end()) {
113 if (it.value() == timeout) {
114 d->killTimer(it.key());
115 it = d->timeouts.erase(it);
122 static void qDBusToggleTimeout(DBusTimeout *timeout, void *data)
127 //qDebug("ToggleTimeout");
129 qDBusRemoveTimeout(timeout, data);
130 qDBusAddTimeout(timeout, data);
133 static dbus_bool_t qDBusAddWatch(DBusWatch *watch, void *data)
138 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
140 int flags = dbus_watch_get_flags(watch);
141 int fd = dbus_watch_get_fd(watch);
143 QDBusConnectionPrivate::Watcher watcher;
144 if (flags & DBUS_WATCH_READABLE) {
145 //qDebug("addReadWatch %d", fd);
146 watcher.watch = watch;
147 if (QCoreApplication::instance()) {
148 watcher.read = new QSocketNotifier(fd, QSocketNotifier::Read, d);
149 watcher.read->setEnabled(dbus_watch_get_enabled(watch));
150 d->connect(watcher.read, SIGNAL(activated(int)), SLOT(socketRead(int)));
153 if (flags & DBUS_WATCH_WRITABLE) {
154 //qDebug("addWriteWatch %d", fd);
155 watcher.watch = watch;
156 if (QCoreApplication::instance()) {
157 watcher.write = new QSocketNotifier(fd, QSocketNotifier::Write, d);
158 watcher.write->setEnabled(dbus_watch_get_enabled(watch));
159 d->connect(watcher.write, SIGNAL(activated(int)), SLOT(socketWrite(int)));
162 d->watchers.insertMulti(fd, watcher);
167 static void qDBusRemoveWatch(DBusWatch *watch, void *data)
172 //qDebug("remove watch");
174 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
175 int fd = dbus_watch_get_fd(watch);
177 QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
178 while (i != d->watchers.end() && i.key() == fd) {
179 if (i.value().watch == watch) {
180 delete i.value().read;
181 delete i.value().write;
182 d->watchers.erase(i);
189 static void qDBusToggleWatch(DBusWatch *watch, void *data)
194 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
195 int fd = dbus_watch_get_fd(watch);
197 QDBusConnectionPrivate::WatcherHash::iterator i = d->watchers.find(fd);
198 while (i != d->watchers.end() && i.key() == fd) {
199 if (i.value().watch == watch) {
200 bool enabled = dbus_watch_get_enabled(watch);
201 int flags = dbus_watch_get_flags(watch);
203 //qDebug("toggle watch %d to %d (write: %d, read: %d)", dbus_watch_get_fd(watch), enabled, flags & DBUS_WATCH_WRITABLE, flags & DBUS_WATCH_READABLE);
205 if (flags & DBUS_WATCH_READABLE && i.value().read)
206 i.value().read->setEnabled(enabled);
207 if (flags & DBUS_WATCH_WRITABLE && i.value().write)
208 i.value().write->setEnabled(enabled);
215 static void qDBusNewConnection(DBusServer *server, DBusConnection *c, void *data)
217 Q_ASSERT(data); Q_ASSERT(server); Q_ASSERT(c);
218 Q_UNUSED(data); Q_UNUSED(server); Q_UNUSED(c);
220 qDebug("SERVER: GOT A NEW CONNECTION"); // TODO
223 extern QDBUS_EXPORT void qDBusSetSpyHook(qDBusSpyHook);
224 void qDBusSetSpyHook(qDBusSpyHook hook)
226 messageSpyHook = hook;
229 #if USE_OUTSIDE_DISPATCH
230 # define HANDLED DBUS_HANDLER_RESULT_HANDLED_OUTSIDE_DISPATCH
231 static DBusHandlerResult qDBusSignalFilterOutside(DBusConnection *connection,
232 DBusMessage *message, void *data)
235 Q_UNUSED(connection);
238 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
239 if (d->mode == QDBusConnectionPrivate::InvalidMode)
240 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; // internal error, actually
242 CallDeliveryEvent *e = d->postedCallDeliveryEvent();
247 return DBUS_HANDLER_RESULT_HANDLED;
250 # define HANDLED DBUS_HANDLER_RESULT_HANDLED
254 static DBusHandlerResult
255 qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
257 return QDBusConnectionPrivate::messageFilter(connection, message, data);
261 DBusHandlerResult QDBusConnectionPrivate::messageFilter(DBusConnection *connection,
262 DBusMessage *message, void *data)
265 Q_UNUSED(connection);
267 QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
268 if (d->mode == QDBusConnectionPrivate::InvalidMode)
269 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
271 QDBusMessage amsg = QDBusMessage::fromDBusMessage(message, QDBusConnection(d->name));
272 qDebug() << "got message:" << amsg;
274 if (messageSpyHook) {
275 qDebug() << "calling the message spy hook";
276 (*messageSpyHook)(amsg);
279 bool handled = false;
280 int msgType = dbus_message_get_type(message);
281 if (msgType == DBUS_MESSAGE_TYPE_SIGNAL) {
282 handled = d->handleSignal(amsg);
283 } else if (msgType == DBUS_MESSAGE_TYPE_METHOD_CALL) {
284 handled = d->handleObjectCall(amsg);
287 return handled ? HANDLED :
288 DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
291 static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode *haystack)
293 foreach (const QDBusConnectionPrivate::ObjectTreeNode::Data &entry, haystack->children)
294 huntAndDestroy(needle, entry.node);
296 if (needle == haystack->obj) {
302 static void huntAndEmit(DBusConnection *connection, DBusMessage *msg,
303 QObject *needle, QDBusConnectionPrivate::ObjectTreeNode *haystack,
304 const QString &path = QString())
306 foreach (const QDBusConnectionPrivate::ObjectTreeNode::Data &entry, haystack->children)
307 huntAndEmit(connection, msg, needle, entry.node, path + QLatin1String("/") + entry.name);
309 if (needle == haystack->obj && haystack->flags & QDBusConnection::ExportAdaptors) {
310 QByteArray p = path.toLatin1();
314 DBusMessage *msg2 = dbus_message_copy(msg);
315 dbus_message_set_path(msg2, p);
316 dbus_connection_send(connection, msg2, 0);
317 dbus_message_unref(msg2);
321 static bool typesMatch(int metaId, int variantType)
323 if (metaId == int(variantType))
326 if (variantType == QVariant::Int && metaId == QMetaType::Short)
329 if (variantType == QVariant::UInt && (metaId == QMetaType::UShort ||
330 metaId == QMetaType::UChar))
333 if (variantType == QVariant::List) {
334 if (metaId == QDBusTypeHelper<bool>::listId() ||
335 metaId == QDBusTypeHelper<short>::listId() ||
336 metaId == QDBusTypeHelper<ushort>::listId() ||
337 metaId == QDBusTypeHelper<int>::listId() ||
338 metaId == QDBusTypeHelper<uint>::listId() ||
339 metaId == QDBusTypeHelper<qlonglong>::listId() ||
340 metaId == QDBusTypeHelper<qulonglong>::listId() ||
341 metaId == QDBusTypeHelper<double>::listId())
345 return false; // no match
348 static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
349 const QDBusTypeList &types, QList<int>& metaTypes)
351 // find the first slot
352 const QMetaObject *super = mo;
353 while (super != &QObject::staticMetaObject &&
354 super != &QDBusAbstractAdaptor::staticMetaObject)
355 super = super->superClass();
357 int attributeMask = (flags & QDBusConnection::ExportAllSlots) ?
358 0 : QMetaMethod::Scriptable;
360 for (int idx = super->methodCount() ; idx <= mo->methodCount(); ++idx) {
361 QMetaMethod mm = mo->method(idx);
364 if (mm.access() != QMetaMethod::Public)
368 // unnecessary, since slots are never public:
369 //if (mm.methodType() != QMetaMethod::Slot)
373 QByteArray sig = QMetaObject::normalizedSignature(mm.signature());
374 int paren = sig.indexOf('(');
375 if (paren != name.length() || !sig.startsWith( name ))
378 int returnType = qDBusNameToTypeId(mm.typeName());
379 bool isAsync = qDBusCheckAsyncTag(mm.tag());
381 // consistency check:
382 if (isAsync && returnType != QMetaType::Void)
385 int inputCount = qDBusParametersForMethod(mm, metaTypes);
386 if (inputCount == -1)
387 continue; // problem parsing
389 metaTypes[0] = returnType;
390 bool hasMessage = false;
391 if (inputCount > 0 &&
392 metaTypes.at(inputCount) == QDBusConnectionPrivate::messageMetaType) {
393 // "no input parameters" is allowed as long as the message meta type is there
398 // try to match the parameters
399 if (inputCount != types.count())
400 continue; // not enough parameters
404 for (i = 0; i < types.count(); ++i)
405 if ( !typesMatch(metaTypes.at(i + 1), types.at(i).qvariantType()) ) {
411 continue; // we didn't match them all
413 // consistency check:
414 if (isAsync && metaTypes.count() > i + 1)
417 if (hasMessage && (mm.attributes() & attributeMask) != attributeMask)
418 continue; // not exported
420 // if we got here, this slot matched
428 static CallDeliveryEvent* prepareReply(QObject *object, int idx, const QList<int> &metaTypes,
429 const QDBusMessage &msg)
433 int n = metaTypes.count() - 1;
434 if (metaTypes[n] == QDBusConnectionPrivate::messageMetaType)
437 // check that types match
438 for (int i = 0; i < n; ++i)
439 if (!typesMatch(metaTypes.at(i + 1), msg.at(i).type()))
440 return 0; // no match
443 // prepare for the call
444 CallDeliveryEvent *data = new CallDeliveryEvent;
445 data->object = object;
448 data->metaTypes = metaTypes;
454 bool QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
455 const QDBusMessage &msg)
457 // This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
458 // that was received from D-Bus
460 // Signals are delivered to slots if the parameters match
461 // Slots can have less parameters than there are on the message
462 // Slots can optionally have one final parameter that is a QDBusMessage
463 // Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
464 CallDeliveryEvent *call = prepareReply(hook.obj, hook.midx, hook.params, msg);
466 postCallDeliveryEvent(call);
472 bool QDBusConnectionPrivate::activateCall(QObject* object, int flags,
473 const QDBusMessage &msg)
475 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call
476 // to a slot on the object.
478 // The call is delivered to the first slot that matches the following conditions:
479 // - has the same name as the message's target name
480 // - ALL of the message's types are found in slot's parameter list
481 // - optionally has one more parameter of type QDBusMessage
482 // If none match, then the slot of the same name as the message target and with
483 // the first type of QDBusMessage is delivered.
485 // Because the marshalling of D-Bus data into QVariant loses the information on
486 // the original types, the message signature is used to determine the original type.
487 // Aside from that, the "int" and "unsigned" types will be tried as well.
489 // The D-Bus specification requires that all MethodCall messages be replied to, unless the
490 // caller specifically waived this requirement. This means that we inspect if the user slot
491 // generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
492 // QDBusMessage parameter, it cannot generate a reply.
494 // When a return message is generated, the slot's return type, if any, will be placed
495 // in the message's first position. If there are non-const reference parameters to the
496 // slot, they must appear at the end and will be placed in the subsequent message
502 QList<int> metaTypes;
506 const QMetaObject *mo = object->metaObject();
507 QDBusTypeList typeList(msg.signature().toUtf8());
508 QByteArray name = msg.name().toUtf8();
510 // find a slot that matches according to the rules above
511 idx = ::findSlot(mo, name, flags, typeList, metaTypes);
513 // try with no parameters, but with a QDBusMessage
514 idx = ::findSlot(mo, name, flags, QDBusTypeList(), metaTypes);
515 if (metaTypes.count() != 2 || metaTypes.at(1) != messageMetaType)
520 // found the slot to be called
521 // prepare for the call:
522 CallDeliveryEvent *call = new CallDeliveryEvent;
525 call->object = object;
530 call->metaTypes = metaTypes;
533 postCallDeliveryEvent(call);
539 void QDBusConnectionPrivate::postCallDeliveryEvent(CallDeliveryEvent *data)
543 #if USE_OUTSIDE_DISPATCH
544 callDeliveryMutex.lock();
545 callDeliveryState = data;
547 QCoreApplication::postEvent( this, data );
551 CallDeliveryEvent *QDBusConnectionPrivate::postedCallDeliveryEvent()
553 CallDeliveryEvent *e = callDeliveryState;
554 Q_ASSERT(e && e->conn == this);
557 callDeliveryState = 0;
558 callDeliveryMutex.unlock();
563 void QDBusConnectionPrivate::deliverCall(const CallDeliveryEvent& data) const
566 const QList<int>& metaTypes = data.metaTypes;
567 const QDBusMessage& msg = data.message;
569 QVarLengthArray<void *, 10> params;
570 params.reserve(metaTypes.count());
572 QVariantList auxParameters;
573 // let's create the parameter list
575 // first one is the return type -- add it below
578 // add the input parameters
580 for (i = 1; i <= msg.count(); ++i) {
581 int id = metaTypes[i];
582 if (id == QDBusConnectionPrivate::messageMetaType)
585 if (id == int(msg.at(i - 1).userType()))
586 // no conversion needed
587 params.append(const_cast<void *>( msg.at(i - 1).constData() ));
589 // convert to what the function expects
590 auxParameters.append(QVariant());
592 const QVariant &in = msg.at(i - 1);
593 QVariant &out = auxParameters[auxParameters.count() - 1];
596 if (id == QVariant::List) {
597 int mid = in.userType();
598 // the only conversion possible here is from a specialised QList<T> to QVariantList
599 if (mid == QDBusTypeHelper<bool>::listId())
600 out = qVariantFromValue(QDBusTypeHelper<bool>::toVariantList(in));
601 else if (mid == QDBusTypeHelper<short>::listId())
602 out = qVariantFromValue(QDBusTypeHelper<short>::toVariantList(in));
603 else if (mid == QDBusTypeHelper<ushort>::listId())
604 out = qVariantFromValue(QDBusTypeHelper<ushort>::toVariantList(in));
605 else if (mid == QDBusTypeHelper<int>::listId())
606 out = qVariantFromValue(QDBusTypeHelper<int>::toVariantList(in));
607 else if (mid == QDBusTypeHelper<uint>::listId())
608 out = qVariantFromValue(QDBusTypeHelper<uint>::toVariantList(in));
609 else if (mid == QDBusTypeHelper<qlonglong>::listId())
610 out = qVariantFromValue(QDBusTypeHelper<qlonglong>::toVariantList(in));
611 else if (mid == QDBusTypeHelper<qulonglong>::listId())
612 out = qVariantFromValue(QDBusTypeHelper<qulonglong>::toVariantList(in));
613 else if (mid == QDBusTypeHelper<double>::listId())
614 out = qVariantFromValue(QDBusTypeHelper<double>::toVariantList(in));
617 } else if (in.type() == QVariant::UInt) {
618 if (id == QMetaType::UChar) {
619 uchar uc = in.toUInt();
620 out = qVariantFromValue(uc);
621 } else if (id == QMetaType::UShort) {
622 ushort us = in.toUInt();
623 out = qVariantFromValue(us);
627 } else if (in.type() == QVariant::Int) {
628 if (id == QMetaType::Short) {
629 short s = in.toInt();
630 out = qVariantFromValue(s);
639 qFatal("Internal error: got invalid meta type %d when trying to convert to meta type %d",
642 params.append( const_cast<void *>(out.constData()) );
646 bool takesMessage = false;
647 if (metaTypes.count() > i && metaTypes[i] == QDBusConnectionPrivate::messageMetaType) {
648 params.append(const_cast<void*>(static_cast<const void*>(&msg)));
654 QVariantList outputArgs;
656 if (metaTypes[0] != QMetaType::Void) {
657 QVariant arg(metaTypes[0], null);
658 outputArgs.append( arg );
659 params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
661 for ( ; i < metaTypes.count(); ++i) {
662 QVariant arg(metaTypes[i], null);
663 outputArgs.append( arg );
664 params.append( const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()) );
669 if (data.object.isNull())
672 fail = data.object->qt_metacall(QMetaObject::InvokeMetaMethod,
673 data.slotIdx, params.data()) >= 0;
675 // do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
677 if (!msg.noReply() && !msg.wasRepliedTo()) {
680 QDBusMessage reply = QDBusMessage::methodReply(msg);
683 qDebug() << "Automatically sending reply:" << reply;
687 // generate internal error
688 QDBusMessage reply = QDBusMessage::error(msg, QDBusError(QDBusError::InternalError,
689 QLatin1String("Failed to deliver message")));
690 qWarning("Internal error: Failed to deliver message");
698 void QDBusConnectionPrivate::customEvent(QEvent *event)
700 // nothing else should be sending custom events at us
701 CallDeliveryEvent* call = static_cast<CallDeliveryEvent *>(event);
704 Q_ASSERT(call->conn == this);
709 QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *parent)
710 : QObject(parent), ref(1), mode(InvalidMode), connection(0), server(0), busService(0)
712 extern bool qDBusInitThreads();
713 static const int msgType = registerMessageMetaType();
714 static const bool threads = qDBusInitThreads();
715 static const bool metatypes = QDBusMetaTypeId::innerInitialize();
721 dbus_error_init(&error);
726 QDBusConnectionPrivate::~QDBusConnectionPrivate()
728 if (dbus_error_is_set(&error))
729 dbus_error_free(&error);
732 rootNode.clear(); // free resources
733 qDeleteAll(cachedMetaObjects);
736 void QDBusConnectionPrivate::closeConnection()
738 QWriteLocker locker(&lock);
739 ConnectionMode oldMode = mode;
740 mode = InvalidMode; // prevent reentrancy
741 if (oldMode == ServerMode) {
743 dbus_server_disconnect(server);
744 dbus_server_unref(server);
747 } else if (oldMode == ClientMode) {
749 dbus_connection_close(connection);
750 // send the "close" message
751 while (dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS)
753 dbus_connection_unref(connection);
759 bool QDBusConnectionPrivate::handleError()
761 lastError = QDBusError(&error);
762 if (dbus_error_is_set(&error))
763 dbus_error_free(&error);
764 return lastError.isValid();
767 void QDBusConnectionPrivate::bindToApplication()
769 // Yay, now that we have an application we are in business
770 Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection",
771 "qDBusBindToApplication called without an application");
772 moveToThread(QCoreApplication::instance()->thread());
774 // Re-add all watchers
775 WatcherHash oldWatchers = watchers;
777 QHashIterator<int, QDBusConnectionPrivate::Watcher> it(oldWatchers);
778 while (it.hasNext()) {
780 if (!it.value().read && !it.value().write) {
781 qDBusAddWatch(it.value().watch, this);
783 watchers.insertMulti(it.key(), it.value());
787 // Re-add all timeouts
788 while (!pendingTimeouts.isEmpty())
789 qDBusAddTimeout(pendingTimeouts.takeFirst(), this);
792 void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
794 DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
795 dbus_timeout_handle(timeout);
798 void QDBusConnectionPrivate::doDispatch()
800 if (mode == ClientMode)
801 while (dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS);
804 void QDBusConnectionPrivate::socketRead(int fd)
806 QHashIterator<int, QDBusConnectionPrivate::Watcher> it(watchers);
807 while (it.hasNext()) {
809 if (it.key() == fd && it.value().read && it.value().read->isEnabled()) {
810 if (!dbus_watch_handle(it.value().watch, DBUS_WATCH_READABLE))
811 qDebug("OUT OF MEM");
818 void QDBusConnectionPrivate::socketWrite(int fd)
820 QHashIterator<int, QDBusConnectionPrivate::Watcher> it(watchers);
821 while (it.hasNext()) {
823 if (it.key() == fd && it.value().write && it.value().write->isEnabled()) {
824 if (!dbus_watch_handle(it.value().watch, DBUS_WATCH_WRITABLE))
825 qDebug("OUT OF MEM");
830 void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
832 QWriteLocker locker(&lock);
833 huntAndDestroy(obj, &rootNode);
835 SignalHookHash::iterator sit = signalHooks.begin();
836 while (sit != signalHooks.end()) {
837 if (static_cast<QObject *>(sit.value().obj) == obj)
838 sit = signalHooks.erase(sit);
843 obj->disconnect(this);
846 void QDBusConnectionPrivate::relaySignal(QObject *obj, const char *interface, const char *name,
847 const QVariantList &args)
849 QReadLocker locker(&lock);
850 QDBusMessage message = QDBusMessage::signal(QLatin1String("/"), QLatin1String(interface),
851 QLatin1String(name));
853 DBusMessage *msg = message.toDBusMessage();
855 qWarning("Could not emit signal %s.%s", interface, name);
859 //qDebug() << "Emitting signal" << message;
860 //qDebug() << "for paths:";
861 dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
862 huntAndEmit(connection, msg, obj, &rootNode);
863 dbus_message_unref(msg);
866 int QDBusConnectionPrivate::registerMessageMetaType()
868 int tp = messageMetaType = qRegisterMetaType<QDBusMessage>("QDBusMessage");
872 int QDBusConnectionPrivate::findSlot(QObject* obj, const QByteArray &normalizedName,
875 int midx = obj->metaObject()->indexOfMethod(normalizedName);
877 qWarning("No such slot '%s' while connecting D-Bus", normalizedName.constData());
881 int inputCount = qDBusParametersForMethod(obj->metaObject()->method(midx), params);
882 if ( inputCount == -1 || inputCount + 1 != params.count() )
883 return -1; // failed to parse or invalid arguments or output arguments
888 bool QDBusConnectionPrivate::prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
889 const QString &service, const QString &path,
890 const QString &interface, const QString &name,
891 QObject *receiver, const char *signal, int minMIdx,
894 QByteArray normalizedName = QMetaObject::normalizedSignature(signal + 1);
895 hook.midx = findSlot(receiver, normalizedName, hook.params);
896 if (hook.midx < minMIdx)
899 hook.sender = service;
903 // build the D-Bus signal name and signature
904 QString mname = name;
905 if (mname.isEmpty()) {
906 normalizedName.truncate(normalizedName.indexOf('('));
907 mname = QString::fromUtf8(normalizedName);
910 key.reserve(interface.length() + 1 + mname.length());
914 if (buildSignature) {
915 hook.signature.clear();
916 for (int i = 1; i < hook.params.count(); ++i)
917 if (hook.params.at(i) != messageMetaType)
918 hook.signature += QLatin1String( QDBusType::dbusSignature( QVariant::Type(hook.params.at(i)) ) );
921 return true; // connect to this signal
924 bool QDBusConnectionPrivate::activateInternalFilters(const ObjectTreeNode *node, const QDBusMessage &msg)
926 // object may be null
928 if (msg.interface().isEmpty() || msg.interface() == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE)) {
929 if (msg.method() == QLatin1String("Introspect") && msg.signature().isEmpty())
930 qDBusIntrospectObject(node, msg);
931 if (msg.interface() == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE))
935 if (node->obj && (msg.interface().isEmpty() ||
936 msg.interface() == QLatin1String(DBUS_INTERFACE_PROPERTIES))) {
937 if (msg.method() == QLatin1String("Get") && msg.signature() == QLatin1String("ss"))
938 qDBusPropertyGet(node, msg);
939 else if (msg.method() == QLatin1String("Set") && msg.signature() == QLatin1String("ssv"))
940 qDBusPropertySet(node, msg);
942 if (msg.interface() == QLatin1String(DBUS_INTERFACE_PROPERTIES))
949 bool QDBusConnectionPrivate::activateObject(const ObjectTreeNode *node, const QDBusMessage &msg)
951 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call to a slot
954 // The call is routed through the adaptor sub-objects if we have any
956 // object may be null
958 QDBusAdaptorConnector *connector;
959 if (node->flags & QDBusConnection::ExportAdaptors &&
960 (connector = qDBusFindAdaptorConnector(node->obj))) {
961 int newflags = node->flags | QDBusConnection::ExportAllSlots;
963 if (msg.interface().isEmpty()) {
964 // place the call in all interfaces
965 // let the first one that handles it to work
966 foreach (const QDBusAdaptorConnector::AdaptorData &entry, connector->adaptors)
967 if (activateCall(entry.adaptor, newflags, msg))
970 // check if we have an interface matching the name that was asked:
971 QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
972 it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
974 if (it != connector->adaptors.end() && it->interface == msg.interface())
975 if (activateCall(it->adaptor, newflags, msg))
980 // no adaptors matched
981 // try our standard filters
982 if (activateInternalFilters(node, msg))
985 // try the object itself:
986 if (node->flags & QDBusConnection::ExportSlots && activateCall(node->obj, node->flags, msg))
990 qDebug("Call failed: no match for %s%s%s at %s",
991 qPrintable(msg.interface()), msg.interface().isEmpty() ? "" : ".",
992 qPrintable(msg.name()),
993 qPrintable(msg.path()));
998 template<typename Func>
999 static bool applyForObject(QDBusConnectionPrivate::ObjectTreeNode *root, const QString &fullpath,
1002 // walk the object tree
1003 QStringList path = fullpath.split(QLatin1Char('/'));
1004 if (path.last().isEmpty())
1005 path.removeLast(); // happens if path is "/"
1007 QDBusConnectionPrivate::ObjectTreeNode *node = root;
1009 // try our own tree first
1010 while (node && !(node->flags & QDBusConnection::ExportChildObjects) ) {
1011 if (i == path.count()) {
1017 QVector<QDBusConnectionPrivate::ObjectTreeNode::Data>::ConstIterator it =
1018 qLowerBound(node->children.constBegin(), node->children.constEnd(), path.at(i));
1019 if (it != node->children.constEnd() && it->name == path.at(i))
1028 // any object in the tree can tell us to switch to its own object tree:
1029 if (node && node->flags & QDBusConnection::ExportChildObjects) {
1030 QObject *obj = node->obj;
1033 if (i == path.count()) {
1034 // we're at the correct level
1035 QDBusConnectionPrivate::ObjectTreeNode fakenode(*node);
1041 const QObjectList children = obj->children();
1043 // find a child with the proper name
1045 foreach (QObject *child, children)
1046 if (child->objectName() == path.at(i)) {
1063 struct qdbus_activateObject
1065 QDBusConnectionPrivate *self;
1066 const QDBusMessage &msg;
1068 inline qdbus_activateObject(QDBusConnectionPrivate *s, const QDBusMessage &m)
1072 inline void operator()(QDBusConnectionPrivate::ObjectTreeNode *node)
1073 { returnVal = self->activateObject(node, msg); }
1076 bool QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
1078 QReadLocker locker(&lock);
1080 qdbus_activateObject apply(this, msg);
1081 if (applyForObject(&rootNode, msg.path(), apply))
1082 return apply.returnVal;
1084 qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
1088 bool QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1090 bool result = false;
1091 SignalHookHash::const_iterator it = signalHooks.find(key);
1092 //qDebug("looking for: %s", path.toLocal8Bit().constData());
1093 //qDebug() << signalHooks.keys();
1094 for ( ; it != signalHooks.constEnd() && it.key() == key; ++it) {
1095 const SignalHook &hook = it.value();
1096 if ( !hook.sender.isEmpty() && hook.sender != msg.sender() )
1098 if ( !hook.path.isEmpty() && hook.path != msg.path() )
1100 if ( !hook.signature.isEmpty() && hook.signature != msg.signature() )
1102 if ( hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1106 result |= activateSignal(hook, msg);
1111 bool QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1113 QString key = msg.member();
1114 key.reserve(key.length() + 1 + msg.interface().length());
1116 key += msg.interface();
1118 QReadLocker locker(&lock);
1119 bool result = handleSignal(key, msg); // one try
1121 key.truncate(msg.member().length() + 1); // keep the ':'
1122 result |= handleSignal(key, msg); // second try
1126 static dbus_int32_t server_slot = -1;
1128 void QDBusConnectionPrivate::setServer(DBusServer *s)
1138 dbus_server_allocate_data_slot(&server_slot);
1139 if (server_slot < 0)
1142 dbus_server_set_watch_functions(server, qDBusAddWatch, qDBusRemoveWatch,
1143 qDBusToggleWatch, this, 0); // ### check return type?
1144 dbus_server_set_timeout_functions(server, qDBusAddTimeout, qDBusRemoveTimeout,
1145 qDBusToggleTimeout, this, 0);
1146 dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1148 dbus_server_set_data(server, server_slot, this, 0);
1151 void QDBusConnectionPrivate::setConnection(DBusConnection *dbc)
1161 dbus_connection_set_exit_on_disconnect(connection, false);
1162 dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1163 qDBusToggleWatch, this, 0);
1164 dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1165 qDBusToggleTimeout, this, 0);
1166 // dbus_bus_add_match(connection, "type='signal',interface='com.trolltech.dbus.Signal'", &error);
1167 // dbus_bus_add_match(connection, "type='signal'", &error);
1169 dbus_bus_add_match(connection, "type='signal'", &error);
1170 if (handleError()) {
1175 const char *service = dbus_bus_get_unique_name(connection);
1177 QVarLengthArray<char, 56> filter;
1178 filter.append("destination='", 13);
1179 filter.append(service, qstrlen(service));
1180 filter.append("\'\0", 2);
1182 dbus_bus_add_match(connection, filter.constData(), &error);
1183 if (handleError()) {
1188 qWarning("QDBusConnectionPrivate::SetConnection: Unable to get base service");
1191 #if USE_OUTSIDE_DISPATCH
1192 dbus_connection_add_filter_outside(connection, qDBusSignalFilter, qDBusSignalFilterOutside, this, 0);
1194 dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1197 //qDebug("base service: %s", service);
1199 // schedule a dispatch:
1200 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1204 static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1206 QDBusConnectionPrivate::messageResultReceived(pending, user_data);
1210 void QDBusConnectionPrivate::messageResultReceived(DBusPendingCall *pending, void *user_data)
1212 QDBusPendingCall *call = reinterpret_cast<QDBusPendingCall *>(user_data);
1213 QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1214 Q_ASSERT(call->pending == pending);
1216 if (!call->receiver.isNull() && call->methodIdx != -1) {
1217 DBusMessage *reply = dbus_pending_call_steal_reply(pending);
1219 // Deliver the return values of a remote function call.
1221 // There is only one connection and it is specified by idx
1222 // The slot must have the same parameter types that the message does
1223 // The slot may have less parameters than the message
1224 // The slot may optionally have one final parameter that is QDBusMessage
1225 // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1227 QDBusMessage msg = QDBusMessage::fromDBusMessage(reply, QDBusConnection(connection->name));
1228 qDebug() << "got message: " << msg;
1229 CallDeliveryEvent *e = prepareReply(call->receiver, call->methodIdx, call->metaTypes, msg);
1231 connection->postCallDeliveryEvent(e);
1233 qDebug() << "Deliver failed!";
1235 dbus_pending_call_unref(pending);
1239 int QDBusConnectionPrivate::send(const QDBusMessage& message) const
1241 DBusMessage *msg = message.toDBusMessage();
1245 dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1247 qDebug() << "sending message:" << message;
1248 bool isOk = dbus_connection_send(connection, msg, 0);
1251 serial = dbus_message_get_serial(msg);
1253 dbus_message_unref(msg);
1257 QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1260 if (!QCoreApplication::instance() || mode == QDBusConnection::NoUseEventLoop) {
1261 DBusMessage *msg = message.toDBusMessage();
1263 return QDBusMessage();
1265 qDebug() << "sending message:" << message;
1266 DBusMessage *reply = dbus_connection_send_with_reply_and_block(connection, msg,
1269 dbus_message_unref(msg);
1271 if (lastError.isValid())
1272 return QDBusMessage::fromError(lastError);
1274 QDBusMessage amsg = QDBusMessage::fromDBusMessage(reply, QDBusConnection(name));
1275 qDebug() << "got message:" << amsg;
1277 if (dbus_connection_get_dispatch_status(connection) == DBUS_DISPATCH_DATA_REMAINS)
1278 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1280 } else { // use the event loop
1281 QDBusReplyWaiter waiter;
1282 if (sendWithReplyAsync(message, &waiter, SLOT(reply(const QDBusMessage&))) > 0) {
1283 // enter the event loop and wait for a reply
1284 waiter.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1286 lastError = waiter.replyMsg; // set or clear error
1287 return waiter.replyMsg;
1290 return QDBusMessage();
1294 int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
1297 if (!receiver || !method || !*method)
1298 // would not be able to deliver a reply
1299 return send(message);
1302 QList<int> metaTypes;
1303 QByteArray normalizedName = QMetaObject::normalizedSignature(method + 1);
1304 slotIdx = findSlot(receiver, normalizedName, metaTypes);
1306 // would not be able to deliver a reply
1307 return send(message);
1309 DBusMessage *msg = message.toDBusMessage();
1313 qDebug() << "sending message:" << message;
1314 DBusPendingCall *pending = 0;
1315 if (dbus_connection_send_with_reply(connection, msg, &pending, message.timeout())) {
1316 if (slotIdx != -1) {
1317 QDBusPendingCall *pcall = new QDBusPendingCall;
1318 pcall->receiver = receiver;
1319 pcall->metaTypes = metaTypes;
1320 pcall->methodIdx = slotIdx;
1321 pcall->connection = this;
1322 pcall->pending = dbus_pending_call_ref(pending);
1323 dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
1325 dbus_pending_call_unref(pending);
1326 return dbus_message_get_serial(msg);
1332 void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
1334 signalHooks.insertMulti(key, hook);
1335 connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)));
1338 void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
1340 connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)));
1342 if (node->flags & QDBusConnection::ExportAdaptors) {
1343 QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
1345 // disconnect and reconnect to avoid duplicates
1346 connector->disconnect(SIGNAL(relaySignal(QObject*,const char*,const char*,QVariantList)),
1347 this, SLOT(relaySignal(QObject*,const char*,const char*,QVariantList)));
1348 connect(connector, SIGNAL(relaySignal(QObject*,const char*,const char*,QVariantList)),
1349 SLOT(relaySignal(QObject*,const char*,const char*,QVariantList)));
1353 void QDBusConnectionPrivate::connectRelay(const QString &service, const QString &path,
1354 const QString &interface,
1355 QDBusAbstractInterface *receiver,
1358 // this function is called by QDBusAbstractInterface when one of its signals is connected
1359 // we set up a relay from D-Bus into it
1362 if (!prepareHook(hook, key, service, path, interface, QString(), receiver, signal,
1363 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
1364 return; // don't connect
1366 // add it to our list:
1367 QWriteLocker locker(&lock);
1368 SignalHookHash::ConstIterator it = signalHooks.find(key);
1369 SignalHookHash::ConstIterator end = signalHooks.end();
1370 for ( ; it != end && it.key() == key; ++it) {
1371 const SignalHook &entry = it.value();
1372 if (entry.sender == hook.sender &&
1373 entry.path == hook.path &&
1374 entry.signature == hook.signature &&
1375 entry.obj == hook.obj &&
1376 entry.midx == hook.midx)
1377 return; // already there, no need to re-add
1380 connectSignal(key, hook);
1383 void QDBusConnectionPrivate::disconnectRelay(const QString &service, const QString &path,
1384 const QString &interface,
1385 QDBusAbstractInterface *receiver,
1388 // this function is called by QDBusAbstractInterface when one of its signals is disconnected
1389 // we remove relay from D-Bus into it
1392 if (!prepareHook(hook, key, service, path, interface, QString(), receiver, signal,
1393 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
1394 return; // don't connect
1396 // remove it from our list:
1397 QWriteLocker locker(&lock);
1398 SignalHookHash::Iterator it = signalHooks.find(key);
1399 SignalHookHash::Iterator end = signalHooks.end();
1400 for ( ; it != end && it.key() == key; ++it) {
1401 const SignalHook &entry = it.value();
1402 if (entry.sender == hook.sender &&
1403 entry.path == hook.path &&
1404 entry.signature == hook.signature &&
1405 entry.obj == hook.obj &&
1406 entry.midx == hook.midx) {
1408 signalHooks.erase(it);
1413 qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
1416 QString QDBusConnectionPrivate::getNameOwner(const QString& name)
1418 if (QDBusUtil::isValidUniqueConnectionName(name))
1420 if (!connection || !QDBusUtil::isValidBusName(name))
1423 QDBusMessage msg = QDBusMessage::methodCall(QLatin1String(DBUS_SERVICE_DBUS),
1424 QLatin1String(DBUS_PATH_DBUS), QLatin1String(DBUS_INTERFACE_DBUS),
1425 QLatin1String("GetNameOwner"));
1427 QDBusMessage reply = sendWithReply(msg, QDBusConnection::NoUseEventLoop);
1428 if (!lastError.isValid() && reply.type() == QDBusMessage::ReplyMessage)
1429 return reply.first().toString();
1433 QDBusInterfacePrivate *
1434 QDBusConnectionPrivate::findInterface(const QString &service,
1435 const QString &path,
1436 const QString &interface)
1438 // check if it's there first -- FIXME: add binding mode
1439 QDBusMetaObject *mo = 0;
1440 QString owner = getNameOwner(service);
1441 if (connection && !owner.isEmpty() && QDBusUtil::isValidObjectPath(path) &&
1442 (interface.isEmpty() || QDBusUtil::isValidInterfaceName(interface)))
1443 // always call here with the unique connection name
1444 mo = findMetaObject(owner, path, interface);
1446 QDBusInterfacePrivate *p = new QDBusInterfacePrivate(QDBusConnection(name), this, owner, path, interface, mo);
1451 p->lastError = lastError;
1452 if (!lastError.isValid()) {
1453 // try to determine why we couldn't get the data
1455 p->lastError = QDBusError(QDBusError::Disconnected,
1456 QLatin1String("Not connected to D-Bus server"));
1457 else if (owner.isEmpty())
1458 p->lastError = QDBusError(QDBusError::ServiceUnknown,
1459 QString(QLatin1String("Service %1 is unknown")).arg(service));
1460 else if (!QDBusUtil::isValidObjectPath(path))
1461 p->lastError = QDBusError(QDBusError::InvalidArgs,
1462 QString(QLatin1String("Object path %1 is invalid")).arg(path));
1463 else if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface))
1464 p->lastError = QDBusError(QDBusError::InvalidArgs,
1465 QString(QLatin1String("Interface %1 is invalid")).arg(interface));
1467 p->lastError = QDBusError(QDBusError::Other, QLatin1String("Unknown error"));
1474 struct qdbus_Introspect
1477 inline void operator()(QDBusConnectionPrivate::ObjectTreeNode *node)
1478 { xml = qDBusIntrospectObject(node); }
1482 QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
1483 const QString &interface)
1485 // service must be a unique connection name
1486 if (!interface.isEmpty()) {
1487 QReadLocker locker(&lock);
1488 QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
1492 if (service == QString::fromUtf8(dbus_bus_get_unique_name(connection))) {
1493 // it's one of our own
1494 QWriteLocker locker(&lock);
1495 QDBusMetaObject *mo = 0;
1496 if (!interface.isEmpty())
1497 mo = cachedMetaObjects.value(interface, 0);
1499 // maybe it got created when we switched from read to write lock
1502 qdbus_Introspect apply;
1503 if (!applyForObject(&rootNode, path, apply)) {
1504 lastError = QDBusError(QDBusError::InvalidArgs,
1505 QString(QLatin1String("No object at %1")).arg(path));
1506 return 0; // no object at path
1509 // release the lock and return
1510 return QDBusMetaObject::createMetaObject(interface, apply.xml, cachedMetaObjects, lastError);
1513 // not local: introspect the target object:
1514 QDBusMessage msg = QDBusMessage::methodCall(service, path,
1515 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
1516 QLatin1String("Introspect"));
1519 QDBusMessage reply = sendWithReply(msg, QDBusConnection::NoUseEventLoop);
1521 // it doesn't exist yet, we have to create it
1522 QWriteLocker locker(&lock);
1523 QDBusMetaObject *mo = 0;
1524 if (!interface.isEmpty())
1525 mo = cachedMetaObjects.value(interface, 0);
1527 // maybe it got created when we switched from read to write lock
1531 if (reply.type() == QDBusMessage::ReplyMessage)
1532 // fetch the XML description
1533 xml = reply.first().toString();
1536 if (reply.type() != QDBusMessage::ErrorMessage || lastError != QDBusError::UnknownMethod)
1540 // release the lock and return
1541 return QDBusMetaObject::createMetaObject(interface, xml, cachedMetaObjects, lastError);
1544 void QDBusReplyWaiter::reply(const QDBusMessage &msg)
1547 QTimer::singleShot(0, this, SLOT(quit()));
1550 #include "qdbusconnection_p.moc"