Merge remote-tracking branch 'origin/api_changes'
[profile/ivi/qtbase.git] / src / dbus / qdbusintegrator.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtDBus module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <qcoreapplication.h>
43 #include <qdebug.h>
44 #include <qmetaobject.h>
45 #include <qobject.h>
46 #include <qsocketnotifier.h>
47 #include <qstringlist.h>
48 #include <qtimer.h>
49 #include <qthread.h>
50
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"
65
66 #include "qdbusthreaddebug_p.h"
67
68 #ifndef QT_NO_DBUS
69
70 QT_BEGIN_NAMESPACE
71
72 static bool isDebugging;
73 #define qDBusDebug              if (!::isDebugging); else qDebug
74
75 Q_GLOBAL_STATIC_WITH_ARGS(const QString, orgFreedesktopDBusString, (QLatin1String(DBUS_SERVICE_DBUS)))
76
77 static inline QString dbusServiceString()
78 { return *orgFreedesktopDBusString(); }
79 static inline QString dbusInterfaceString()
80 {
81     // it's the same string, but just be sure
82     Q_ASSERT(*orgFreedesktopDBusString() == QLatin1String(DBUS_INTERFACE_DBUS));
83     return *orgFreedesktopDBusString();
84 }
85
86 static inline QDebug operator<<(QDebug dbg, const QThread *th)
87 {
88     dbg.nospace() << "QThread(ptr=" << (void*)th;
89     if (th && !th->objectName().isEmpty())
90         dbg.nospace() << ", name=" << th->objectName();
91     dbg.nospace() << ')';
92     return dbg.space();
93 }
94
95 #if QDBUS_THREAD_DEBUG
96 static inline QDebug operator<<(QDebug dbg, const QDBusConnectionPrivate *conn)
97 {
98     dbg.nospace() << "QDBusConnection("
99                   << "ptr=" << (void*)conn
100                   << ", name=" << conn->name
101                   << ", baseService=" << conn->baseService
102                   << ", thread=";
103     if (conn->thread() == QThread::currentThread())
104         dbg.nospace() << "same thread";
105     else
106         dbg.nospace() << conn->thread();
107     dbg.nospace() << ')';
108     return dbg.space();
109 }
110
111 Q_AUTOTEST_EXPORT void qdbusDefaultThreadDebug(int action, int condition, QDBusConnectionPrivate *conn)
112 {
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" :
127                      "condition unknown")
128                  << "in connection" << conn;
129 }
130 Q_AUTOTEST_EXPORT qdbusThreadDebugFunc qdbusThreadDebug = 0;
131 #endif
132
133 typedef void (*QDBusSpyHook)(const QDBusMessage&);
134 typedef QVarLengthArray<QDBusSpyHook, 4> QDBusSpyHookList;
135 Q_GLOBAL_STATIC(QDBusSpyHookList, qDBusSpyHookList)
136
137 extern "C" {
138
139     // libdbus-1 callbacks
140
141 static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms);
142 static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
143 {
144     Q_ASSERT(timeout);
145     Q_ASSERT(data);
146
147   //  qDebug("addTimeout %d", q_dbus_timeout_get_interval(timeout));
148
149     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
150
151     if (!q_dbus_timeout_get_enabled(timeout))
152         return true;
153
154     QDBusWatchAndTimeoutLocker locker(AddTimeoutAction, d);
155     if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
156         // correct thread
157         return qDBusRealAddTimeout(d, timeout, q_dbus_timeout_get_interval(timeout));
158     } else {
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);
164         return true;
165     }
166 }
167
168 static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms)
169 {
170     Q_ASSERT(d->timeouts.keys(timeout).isEmpty());
171
172     int timerId = d->startTimer(ms);
173     if (!timerId)
174         return false;
175
176     d->timeouts[timerId] = timeout;
177     return true;
178 }
179
180 static void qDBusRemoveTimeout(DBusTimeout *timeout, void *data)
181 {
182     Q_ASSERT(timeout);
183     Q_ASSERT(data);
184
185   //  qDebug("removeTimeout");
186
187     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
188
189     QDBusWatchAndTimeoutLocker locker(RemoveTimeoutAction, d);
190
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);
196         else
197             ++pit;
198     }
199
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) {
205             if (correctThread) {
206                 // correct thread
207                 d->killTimer(it.key());
208             } else {
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);
214             }
215             it = d->timeouts.erase(it);
216             break;
217         } else {
218             ++it;
219         }
220     }
221 }
222
223 static void qDBusToggleTimeout(DBusTimeout *timeout, void *data)
224 {
225     Q_ASSERT(timeout);
226     Q_ASSERT(data);
227
228     //qDebug("ToggleTimeout");
229
230     qDBusRemoveTimeout(timeout, data);
231     qDBusAddTimeout(timeout, data);
232 }
233
234 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd);
235 static dbus_bool_t qDBusAddWatch(DBusWatch *watch, void *data)
236 {
237     Q_ASSERT(watch);
238     Q_ASSERT(data);
239
240     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
241
242     int flags = q_dbus_watch_get_flags(watch);
243     int fd = q_dbus_watch_get_fd(watch);
244
245     if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
246         return qDBusRealAddWatch(d, watch, flags, fd);
247     } else {
248         QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
249         ev->subtype = QDBusConnectionCallbackEvent::AddWatch;
250         ev->watch = watch;
251         ev->fd = fd;
252         ev->extra = flags;
253         d->postEventToThread(AddWatchAction, d, ev);
254         return true;
255     }
256 }
257
258 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd)
259 {
260     QDBusConnectionPrivate::Watcher watcher;
261
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)));
270         }
271     }
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)));
279         }
280     }
281     d->watchers.insertMulti(fd, watcher);
282
283     return true;
284 }
285
286 static void qDBusRemoveWatch(DBusWatch *watch, void *data)
287 {
288     Q_ASSERT(watch);
289     Q_ASSERT(data);
290
291     //qDebug("remove watch");
292
293     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
294     int fd = q_dbus_watch_get_fd(watch);
295
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;
304             } else {
305                 // incorrect thread or no application, use delete later
306                 if (i->read)
307                     i->read->deleteLater();
308                 if (i->write)
309                     i->write->deleteLater();
310             }
311             i = d->watchers.erase(i);
312         } else {
313             ++i;
314         }
315     }
316 }
317
318 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd);
319 static void qDBusToggleWatch(DBusWatch *watch, void *data)
320 {
321     Q_ASSERT(watch);
322     Q_ASSERT(data);
323
324     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
325     int fd = q_dbus_watch_get_fd(watch);
326
327     if (QCoreApplication::instance() && QThread::currentThread() == d->thread()) {
328         qDBusRealToggleWatch(d, watch, fd);
329     } else {
330         QDBusConnectionCallbackEvent *ev = new QDBusConnectionCallbackEvent;
331         ev->subtype = QDBusConnectionCallbackEvent::ToggleWatch;
332         ev->watch = watch;
333         ev->fd = fd;
334         d->postEventToThread(ToggleWatchAction, d, ev);
335     }
336 }
337
338 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd)
339 {
340     QDBusWatchAndTimeoutLocker locker(ToggleWatchAction, d);
341
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);
347
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);
349
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);
354             return;
355         }
356         ++i;
357     }
358 }
359
360 static void qDBusUpdateDispatchStatus(DBusConnection *connection, DBusDispatchStatus new_status, void *data)
361 {
362     Q_ASSERT(connection);
363     Q_UNUSED(connection);
364     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
365
366     static int slotId; // 0 is QObject::deleteLater()
367     if (!slotId) {
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()");
371     }
372
373     //qDBusDebug() << "Updating dispatcher status" << slotId;
374     if (new_status == DBUS_DISPATCH_DATA_REMAINS)
375         QDBusConnectionPrivate::staticMetaObject.method(slotId).
376             invoke(d, Qt::QueuedConnection);
377 }
378
379 static void qDBusNewConnection(DBusServer *server, DBusConnection *connection, void *data)
380 {
381     // ### We may want to separate the server from the QDBusConnectionPrivate
382     Q_ASSERT(server); Q_UNUSED(server);
383     Q_ASSERT(connection);
384     Q_ASSERT(data);
385
386     // keep the connection alive
387     q_dbus_connection_ref(connection);
388     QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(data);
389
390     // setPeer does the error handling for us
391     QDBusErrorInternal error;
392     d->setPeer(connection, error);
393
394     QDBusConnection retval = QDBusConnectionPrivate::q(d);
395
396     // make QDBusServer emit the newConnection signal
397     d->serverConnection(retval);
398 }
399
400 } // extern "C"
401
402 static QByteArray buildMatchRule(const QString &service,
403                                  const QString &objectPath, const QString &interface,
404                                  const QString &member, const QStringList &argMatch, const QString & /*signature*/)
405 {
406     QString result = QLatin1String("type='signal',");
407     QString keyValue = QLatin1String("%1='%2',");
408
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);
417
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));
424     }
425
426     result.chop(1);             // remove ending comma
427     return result.toLatin1();
428 }
429
430 static bool findObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
431                        const QString &fullpath, int &usedLength,
432                        QDBusConnectionPrivate::ObjectTreeNode &result)
433 {
434     if (!fullpath.compare(QLatin1String("/")) && root->obj) {
435         usedLength = 1;
436         result = *root;
437         return root;
438     }
439     int start = 0;
440     int length = fullpath.length();
441     if (fullpath.at(0) == QLatin1Char('/'))
442         start = 1;
443
444     // walk the object tree
445     const QDBusConnectionPrivate::ObjectTreeNode *node = root;
446     while (start < length && node) {
447         if (node->flags & QDBusConnection::ExportChildObjects)
448             break;
449         if ((node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath))
450             break;
451         int end = fullpath.indexOf(QLatin1Char('/'), start);
452         end = (end == -1 ? length : end);
453         QStringRef pathComponent(&fullpath, start, end - start);
454
455         QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
456             qLowerBound(node->children.constBegin(), node->children.constEnd(), pathComponent);
457         if (it != node->children.constEnd() && it->name == pathComponent)
458             // match
459             node = it;
460         else
461             node = 0;
462
463         start = end + 1;
464     }
465
466     // found our object
467     usedLength = (start > length ? length : start);
468     if (node) {
469         if (node->obj || !node->children.isEmpty())
470             result = *node;
471         else
472             // there really is no object here
473             // we're just looking at an unused space in the QVector
474             node = 0;
475     }
476     return node;
477 }
478
479 static QObject *findChildObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
480                                 const QString &fullpath, int start)
481 {
482     int length = fullpath.length();
483
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;
488
489         while (obj) {
490             if (start >= length)
491                 // we're at the correct level
492                 return obj;
493
494             int pos = fullpath.indexOf(QLatin1Char('/'), start);
495             pos = (pos == -1 ? length : pos);
496             QStringRef pathComponent(&fullpath, start, pos - start);
497
498             const QObjectList children = obj->children();
499
500             // find a child with the proper name
501             QObject *next = 0;
502             QObjectList::ConstIterator it = children.constBegin();
503             QObjectList::ConstIterator end = children.constEnd();
504             for ( ; it != end; ++it)
505                 if ((*it)->objectName() == pathComponent) {
506                     next = *it;
507                     break;
508                 }
509
510             if (!next)
511                 break;
512
513             obj = next;
514             start = pos + 1;
515         }
516     }
517
518     // object not found
519     return 0;
520 }
521
522 static bool shouldWatchService(const QString &service)
523 {
524     return !service.isEmpty() && !service.startsWith(QLatin1Char(':'));
525 }
526
527 extern Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook);
528 void qDBusAddSpyHook(QDBusSpyHook hook)
529 {
530     qDBusSpyHookList()->append(hook);
531 }
532
533 extern "C" {
534 static DBusHandlerResult
535 qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
536 {
537     Q_ASSERT(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;
542
543     QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(message, d->capabilities);
544     qDBusDebug() << d << "got message (signal):" << amsg;
545
546     return d->handleMessage(amsg) ?
547         DBUS_HANDLER_RESULT_HANDLED :
548         DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
549 }
550 }
551
552 bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
553 {
554     const QDBusSpyHookList *list = qDBusSpyHookList();
555     for (int i = 0; i < list->size(); ++i) {
556         qDBusDebug() << "calling the message spy hook";
557         (*(*list)[i])(amsg);
558     }
559
560     if (!ref.load())
561         return false;
562
563     switch (amsg.type()) {
564     case QDBusMessage::SignalMessage:
565         handleSignal(amsg);
566         // if there are any other filters in this DBusConnection,
567         // let them see the signal too
568         return false;
569     case QDBusMessage::MethodCallMessage:
570         handleObjectCall(amsg);
571         return true;
572     case QDBusMessage::ReplyMessage:
573     case QDBusMessage::ErrorMessage:
574     case QDBusMessage::InvalidMessage:
575         return false;           // we don't handle those here
576     }
577
578     return false;
579 }
580
581 static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode &haystack)
582 {
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);
587
588     if (needle == haystack.obj) {
589         haystack.obj = 0;
590         haystack.flags = 0;
591     }
592 }
593
594 static void huntAndEmit(DBusConnection *connection, DBusMessage *msg,
595                         QObject *needle, const QDBusConnectionPrivate::ObjectTreeNode &haystack,
596                         bool isScriptable, bool isAdaptor, const QString &path = QString())
597 {
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);
602
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
613         }
614
615         QByteArray p = path.toLatin1();
616         if (p.isEmpty())
617             p = "/";
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);
623     }
624 }
625
626 static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
627                     const QString &signature_, QVector<int> &metaTypes)
628 {
629     QByteArray msgSignature = signature_.toLatin1();
630
631     for (int idx = mo->methodCount() - 1 ; idx >= QObject::staticMetaObject.methodCount(); --idx) {
632         QMetaMethod mm = mo->method(idx);
633
634         // check access:
635         if (mm.access() != QMetaMethod::Public)
636             continue;
637
638         // check type:
639         if (mm.methodType() != QMetaMethod::Slot && mm.methodType() != QMetaMethod::Method)
640             continue;
641
642         // check name:
643         if (mm.name() != name)
644             continue;
645
646         int returnType = mm.returnType();
647         bool isAsync = qDBusCheckAsyncTag(mm.tag());
648         bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
649
650         // consistency check:
651         if (isAsync && returnType != QMetaType::Void)
652             continue;
653
654         int inputCount = qDBusParametersForMethod(mm, metaTypes);
655         if (inputCount == -1)
656             continue;           // problem parsing
657
658         metaTypes[0] = returnType;
659         bool hasMessage = false;
660         if (inputCount > 0 &&
661             metaTypes.at(inputCount) == QDBusMetaTypeId::message) {
662             // "no input parameters" is allowed as long as the message meta type is there
663             hasMessage = true;
664             --inputCount;
665         }
666
667         // try to match the parameters
668         int i;
669         QByteArray reconstructedSignature;
670         for (i = 1; i <= inputCount; ++i) {
671             const char *typeSignature = QDBusMetaType::typeToSignature( metaTypes.at(i) );
672             if (!typeSignature)
673                 break;          // invalid
674
675             reconstructedSignature += typeSignature;
676             if (!msgSignature.startsWith(reconstructedSignature))
677                 break;
678         }
679
680         if (reconstructedSignature != msgSignature)
681             continue;           // we didn't match them all
682
683         if (hasMessage)
684             ++i;
685
686         // make sure that the output parameters have signatures too
687         if (returnType != QMetaType::UnknownType && returnType != QMetaType::Void && QDBusMetaType::typeToSignature(returnType) == 0)
688             continue;
689
690         bool ok = true;
691         for (int j = i; ok && j < metaTypes.count(); ++j)
692             if (QDBusMetaType::typeToSignature(metaTypes.at(i)) == 0)
693                 ok = false;
694         if (!ok)
695             continue;
696
697         // consistency check:
698         if (isAsync && metaTypes.count() > i + 1)
699             continue;
700
701         if (mm.methodType() == QMetaMethod::Slot) {
702             if (isScriptable && (flags & QDBusConnection::ExportScriptableSlots) == 0)
703                 continue;           // scriptable slots not exported
704             if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableSlots) == 0)
705                 continue;           // non-scriptable slots not exported
706         } else {
707             if (isScriptable && (flags & QDBusConnection::ExportScriptableInvokables) == 0)
708                 continue;           // scriptable invokables not exported
709             if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableInvokables) == 0)
710                 continue;           // non-scriptable invokables not exported
711         }
712
713         // if we got here, this slot matched
714         return idx;
715     }
716
717     // no slot matched
718     return -1;
719 }
720
721 static QDBusCallDeliveryEvent * const DIRECT_DELIVERY = (QDBusCallDeliveryEvent *)1;
722
723 QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
724                                                              QObject *object, int idx,
725                                                              const QVector<int> &metaTypes,
726                                                              const QDBusMessage &msg)
727 {
728     Q_ASSERT(object);
729     Q_UNUSED(object);
730
731     int n = metaTypes.count() - 1;
732     if (metaTypes[n] == QDBusMetaTypeId::message)
733         --n;
734
735     if (msg.arguments().count() < n)
736         return 0;               // too few arguments
737
738     // check that types match
739     for (int i = 0; i < n; ++i)
740         if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() &&
741             msg.arguments().at(i).userType() != qMetaTypeId<QDBusArgument>())
742             return 0;           // no match
743
744     // we can deliver
745     // prepare for the call
746     if (target == object)
747         return DIRECT_DELIVERY;
748     return new QDBusCallDeliveryEvent(QDBusConnection(target), idx, target, msg, metaTypes);
749 }
750
751 void QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
752                                             const QDBusMessage &msg)
753 {
754     // This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
755     // that was received from D-Bus
756     //
757     // Signals are delivered to slots if the parameters match
758     // Slots can have less parameters than there are on the message
759     // Slots can optionally have one final parameter that is a QDBusMessage
760     // Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
761     QDBusCallDeliveryEvent *call = prepareReply(this, hook.obj, hook.midx, hook.params, msg);
762     if (call == DIRECT_DELIVERY) {
763         // short-circuit delivery
764         Q_ASSERT(this == hook.obj);
765         deliverCall(this, 0, msg, hook.params, hook.midx);
766         return;
767     }
768     if (call)
769         postEventToThread(ActivateSignalAction, hook.obj, call);
770 }
771
772 bool QDBusConnectionPrivate::activateCall(QObject* object, int flags, const QDBusMessage &msg)
773 {
774     // This is called by QDBusConnectionPrivate::handleObjectCall to place a call
775     // to a slot on the object.
776     //
777     // The call is delivered to the first slot that matches the following conditions:
778     //  - has the same name as the message's target member
779     //  - ALL of the message's types are found in slot's parameter list
780     //  - optionally has one more parameter of type QDBusMessage
781     // If none match, then the slot of the same name as the message target and with
782     // the first type of QDBusMessage is delivered.
783     //
784     // The D-Bus specification requires that all MethodCall messages be replied to, unless the
785     // caller specifically waived this requirement. This means that we inspect if the user slot
786     // generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
787     // QDBusMessage parameter, it cannot generate a reply.
788     //
789     // When a return message is generated, the slot's return type, if any, will be placed
790     // in the message's first position. If there are non-const reference parameters to the
791     // slot, they must appear at the end and will be placed in the subsequent message
792     // positions.
793
794     static const char cachePropertyName[] = "_qdbus_slotCache";
795
796     if (!object)
797         return false;
798
799 #ifndef QT_NO_PROPERTIES
800     Q_ASSERT_X(QThread::currentThread() == object->thread(),
801                "QDBusConnection: internal threading error",
802                "function called for an object that is in another thread!!");
803
804     QDBusSlotCache slotCache =
805         qvariant_cast<QDBusSlotCache>(object->property(cachePropertyName));
806     QString cacheKey = msg.member(), signature = msg.signature();
807     if (!signature.isEmpty()) {
808         cacheKey.reserve(cacheKey.length() + 1 + signature.length());
809         cacheKey += QLatin1Char('.');
810         cacheKey += signature;
811     }
812
813     QDBusSlotCache::Hash::ConstIterator cacheIt = slotCache.hash.constFind(cacheKey);
814     while (cacheIt != slotCache.hash.constEnd() && cacheIt->flags != flags &&
815            cacheIt.key() == cacheKey)
816         ++cacheIt;
817     if (cacheIt == slotCache.hash.constEnd() || cacheIt.key() != cacheKey)
818     {
819         // not cached, analyze the meta object
820         const QMetaObject *mo = object->metaObject();
821         QByteArray memberName = msg.member().toUtf8();
822
823         // find a slot that matches according to the rules above
824         QDBusSlotCache::Data slotData;
825         slotData.flags = flags;
826         slotData.slotIdx = ::findSlot(mo, memberName, flags, msg.signature(), slotData.metaTypes);
827         if (slotData.slotIdx == -1) {
828             // ### this is where we want to add the connection as an arg too
829             // try with no parameters, but with a QDBusMessage
830             slotData.slotIdx = ::findSlot(mo, memberName, flags, QString(), slotData.metaTypes);
831             if (slotData.metaTypes.count() != 2 ||
832                 slotData.metaTypes.at(1) != QDBusMetaTypeId::message) {
833                 // not found
834                 // save the negative lookup
835                 slotData.slotIdx = -1;
836                 slotData.metaTypes.clear();
837                 slotCache.hash.insert(cacheKey, slotData);
838                 object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
839                 return false;
840             }
841         }
842
843         // save to the cache
844         slotCache.hash.insert(cacheKey, slotData);
845         object->setProperty(cachePropertyName, QVariant::fromValue(slotCache));
846
847         // found the slot to be called
848         deliverCall(object, flags, msg, slotData.metaTypes, slotData.slotIdx);
849         return true;
850     } else if (cacheIt->slotIdx == -1) {
851         // negative cache
852         return false;
853     } else {
854         // use the cache
855         deliverCall(object, flags, msg, cacheIt->metaTypes, cacheIt->slotIdx);
856         return true;
857     }
858 #endif // QT_NO_PROPERTIES
859     return false;
860 }
861
862 void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const QDBusMessage &msg,
863                                          const QVector<int> &metaTypes, int slotIdx)
864 {
865     Q_ASSERT_X(!object || QThread::currentThread() == object->thread(),
866                "QDBusConnection: internal threading error",
867                "function called for an object that is in another thread!!");
868
869     QVarLengthArray<void *, 10> params;
870     params.reserve(metaTypes.count());
871
872     QVariantList auxParameters;
873     // let's create the parameter list
874
875     // first one is the return type -- add it below
876     params.append(0);
877
878     // add the input parameters
879     int i;
880     int pCount = qMin(msg.arguments().count(), metaTypes.count() - 1);
881     for (i = 1; i <= pCount; ++i) {
882         int id = metaTypes[i];
883         if (id == QDBusMetaTypeId::message)
884             break;
885
886         const QVariant &arg = msg.arguments().at(i - 1);
887         if (arg.userType() == id)
888             // no conversion needed
889             params.append(const_cast<void *>(arg.constData()));
890         else if (arg.userType() == qMetaTypeId<QDBusArgument>()) {
891             // convert to what the function expects
892             void *null = 0;
893             auxParameters.append(QVariant(id, null));
894
895             const QDBusArgument &in =
896                 *reinterpret_cast<const QDBusArgument *>(arg.constData());
897             QVariant &out = auxParameters[auxParameters.count() - 1];
898
899             if (!QDBusMetaType::demarshall(in, out.userType(), out.data()))
900                 qFatal("Internal error: demarshalling function for type '%s' (%d) failed!",
901                        out.typeName(), out.userType());
902
903             params.append(const_cast<void *>(out.constData()));
904         } else {
905             qFatal("Internal error: got invalid meta type %d (%s) "
906                    "when trying to convert to meta type %d (%s)",
907                    arg.userType(), QMetaType::typeName(arg.userType()),
908                    id, QMetaType::typeName(id));
909         }
910     }
911
912     if (metaTypes.count() > i && metaTypes[i] == QDBusMetaTypeId::message) {
913         params.append(const_cast<void*>(static_cast<const void*>(&msg)));
914         ++i;
915     }
916
917     // output arguments
918     QVariantList outputArgs;
919     void *null = 0;
920     if (metaTypes[0] != QMetaType::Void && metaTypes[0] != QMetaType::UnknownType) {
921         QVariant arg(metaTypes[0], null);
922         outputArgs.append( arg );
923         params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
924     }
925     for ( ; i < metaTypes.count(); ++i) {
926         QVariant arg(metaTypes[i], null);
927         outputArgs.append( arg );
928         params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
929     }
930
931     // make call:
932     bool fail;
933     if (!object) {
934         fail = true;
935     } else {
936         // FIXME: save the old sender!
937         QDBusContextPrivate context(QDBusConnection(this), msg);
938         QDBusContextPrivate *old = QDBusContextPrivate::set(object, &context);
939         QDBusConnectionPrivate::setSender(this);
940
941         QPointer<QObject> ptr = object;
942         fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
943                                    slotIdx, params.data()) >= 0;
944         QDBusConnectionPrivate::setSender(0);
945         // the object might be deleted in the slot
946         if (!ptr.isNull())
947             QDBusContextPrivate::set(object, old);
948     }
949
950     // do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
951     // yet.
952     if (msg.isReplyRequired() && !msg.isDelayedReply()) {
953         if (!fail) {
954             // normal reply
955             qDBusDebug() << this << "Automatically sending reply:" << outputArgs;
956             send(msg.createReply(outputArgs));
957         } else {
958             // generate internal error
959             qWarning("Internal error: Failed to deliver message");
960             send(msg.createErrorReply(QDBusError::InternalError,
961                                       QLatin1String("Failed to deliver message")));
962         }
963     }
964
965     return;
966 }
967
968 extern bool qDBusInitThreads();
969
970 QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
971     : QObject(p), ref(1), capabilities(0), mode(InvalidMode), connection(0), server(0), busService(0),
972       watchAndTimeoutLock(QMutex::Recursive),
973       rootNode(QString(QLatin1Char('/')))
974 {
975     static const bool threads = q_dbus_threads_init_default();
976     static const int debugging = qgetenv("QDBUS_DEBUG").toInt();
977     ::isDebugging = debugging;
978     Q_UNUSED(threads)
979     Q_UNUSED(debugging)
980
981 #ifdef QDBUS_THREAD_DEBUG
982     if (debugging > 1)
983         qdbusThreadDebug = qdbusDefaultThreadDebug;
984 #endif
985
986     QDBusMetaTypeId::init();
987
988     rootNode.flags = 0;
989
990     // prepopulate watchedServices:
991     // we know that the owner of org.freedesktop.DBus is itself
992     watchedServices.insert(dbusServiceString(), WatchedServiceData(dbusServiceString(), 1));
993
994     // prepopulate matchRefCounts:
995     // we know that org.freedesktop.DBus will never change owners
996     matchRefCounts.insert("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.DBus'", 1);
997 }
998
999 QDBusConnectionPrivate::~QDBusConnectionPrivate()
1000 {
1001     if (thread() && thread() != QThread::currentThread())
1002         qWarning("QDBusConnection(name=\"%s\")'s last reference in not in its creation thread! "
1003                  "Timer and socket errors will follow and the program will probably crash",
1004                  qPrintable(name));
1005
1006     closeConnection();
1007     rootNode.children.clear();  // free resources
1008     qDeleteAll(cachedMetaObjects);
1009
1010     if (server)
1011         q_dbus_server_unref(server);
1012     if (connection)
1013         q_dbus_connection_unref(connection);
1014
1015     connection = 0;
1016     server = 0;
1017 }
1018
1019 void QDBusConnectionPrivate::deleteYourself()
1020 {
1021     if (thread() && thread() != QThread::currentThread()) {
1022         // last reference dropped while not in the correct thread
1023         // ask the correct thread to delete
1024
1025         // note: since we're posting an event to another thread, we
1026         // must consider deleteLater() to take effect immediately
1027         deleteLater();
1028     } else {
1029         delete this;
1030     }
1031 }
1032
1033 void QDBusConnectionPrivate::closeConnection()
1034 {
1035     QDBusWriteLocker locker(CloseConnectionAction, this);
1036     ConnectionMode oldMode = mode;
1037     mode = InvalidMode; // prevent reentrancy
1038     baseService.clear();
1039
1040     if (server)
1041         q_dbus_server_disconnect(server);
1042
1043     if (oldMode == ClientMode || oldMode == PeerMode) {
1044         if (connection) {
1045             q_dbus_connection_close(connection);
1046             // send the "close" message
1047             while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS)
1048                 ;
1049         }
1050     }
1051 }
1052
1053 void QDBusConnectionPrivate::checkThread()
1054 {
1055     if (!thread()) {
1056         if (QCoreApplication::instance())
1057             moveToThread(QCoreApplication::instance()->thread());
1058         else
1059             qWarning("The thread that had QDBusConnection('%s') has died and there is no main thread",
1060                      qPrintable(name));
1061     }
1062 }
1063
1064 bool QDBusConnectionPrivate::handleError(const QDBusErrorInternal &error)
1065 {
1066     if (!error)
1067         return false;           // no error
1068
1069     //lock.lockForWrite();
1070     lastError = error;
1071     //lock.unlock();
1072     return true;
1073 }
1074
1075 void QDBusConnectionPrivate::timerEvent(QTimerEvent *e)
1076 {
1077     {
1078         QDBusWatchAndTimeoutLocker locker(TimerEventAction, this);
1079         DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
1080         if (timeout)
1081             q_dbus_timeout_handle(timeout);
1082     }
1083
1084     doDispatch();
1085 }
1086
1087 void QDBusConnectionPrivate::customEvent(QEvent *e)
1088 {
1089     Q_ASSERT(e->type() == QEvent::User);
1090
1091     QDBusConnectionCallbackEvent *ev = static_cast<QDBusConnectionCallbackEvent *>(e);
1092     QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1093                                         QDBusLockerBase::BeforeDeliver, this);
1094     switch (ev->subtype)
1095     {
1096     case QDBusConnectionCallbackEvent::AddTimeout: {
1097         QDBusWatchAndTimeoutLocker locker(RealAddTimeoutAction, this);
1098         while (!timeoutsPendingAdd.isEmpty()) {
1099             QPair<DBusTimeout *, int> entry = timeoutsPendingAdd.takeFirst();
1100             qDBusRealAddTimeout(this, entry.first, entry.second);
1101         }
1102         break;
1103     }
1104
1105     case QDBusConnectionCallbackEvent::KillTimer:
1106         killTimer(ev->timerId);
1107         break;
1108
1109     case QDBusConnectionCallbackEvent::AddWatch:
1110         qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
1111         break;
1112
1113     case QDBusConnectionCallbackEvent::ToggleWatch:
1114         qDBusRealToggleWatch(this, ev->watch, ev->fd);
1115         break;
1116     }
1117     QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1118                                         QDBusLockerBase::AfterDeliver, this);
1119 }
1120
1121 void QDBusConnectionPrivate::doDispatch()
1122 {
1123     QDBusDispatchLocker locker(DoDispatchAction, this);
1124     if (mode == ClientMode || mode == PeerMode)
1125         while (q_dbus_connection_dispatch(connection) == DBUS_DISPATCH_DATA_REMAINS) ;
1126 }
1127
1128 void QDBusConnectionPrivate::socketRead(int fd)
1129 {
1130     QVarLengthArray<DBusWatch *, 2> pendingWatches;
1131
1132     {
1133         QDBusWatchAndTimeoutLocker locker(SocketReadAction, this);
1134         WatcherHash::ConstIterator it = watchers.constFind(fd);
1135         while (it != watchers.constEnd() && it.key() == fd) {
1136             if (it->watch && it->read && it->read->isEnabled())
1137                 pendingWatches.append(it.value().watch);
1138             ++it;
1139         }
1140     }
1141
1142     for (int i = 0; i < pendingWatches.size(); ++i)
1143         if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_READABLE))
1144             qDebug("OUT OF MEM");
1145     doDispatch();
1146 }
1147
1148 void QDBusConnectionPrivate::socketWrite(int fd)
1149 {
1150     QVarLengthArray<DBusWatch *, 2> pendingWatches;
1151
1152     {
1153         QDBusWatchAndTimeoutLocker locker(SocketWriteAction, this);
1154         WatcherHash::ConstIterator it = watchers.constFind(fd);
1155         while (it != watchers.constEnd() && it.key() == fd) {
1156             if (it->watch && it->write && it->write->isEnabled())
1157                 pendingWatches.append(it.value().watch);
1158             ++it;
1159         }
1160     }
1161
1162     for (int i = 0; i < pendingWatches.size(); ++i)
1163         if (!q_dbus_watch_handle(pendingWatches[i], DBUS_WATCH_WRITABLE))
1164             qDebug("OUT OF MEM");
1165 }
1166
1167 void QDBusConnectionPrivate::objectDestroyed(QObject *obj)
1168 {
1169     QDBusWriteLocker locker(ObjectDestroyedAction, this);
1170     huntAndDestroy(obj, rootNode);
1171
1172     SignalHookHash::iterator sit = signalHooks.begin();
1173     while (sit != signalHooks.end()) {
1174         if (static_cast<QObject *>(sit.value().obj) == obj)
1175             sit = disconnectSignal(sit);
1176         else
1177             ++sit;
1178     }
1179
1180     obj->disconnect(this);
1181 }
1182
1183 void QDBusConnectionPrivate::relaySignal(QObject *obj, const QMetaObject *mo, int signalId,
1184                                          const QVariantList &args)
1185 {
1186     QString interface = qDBusInterfaceFromMetaObject(mo);
1187
1188     QMetaMethod mm = mo->method(signalId);
1189     QByteArray memberName = mm.name();
1190
1191     // check if it's scriptable
1192     bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
1193     bool isAdaptor = false;
1194     for ( ; mo; mo = mo->superClass())
1195         if (mo == &QDBusAbstractAdaptor::staticMetaObject) {
1196             isAdaptor = true;
1197             break;
1198         }
1199
1200     QDBusReadLocker locker(RelaySignalAction, this);
1201     QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/"), interface,
1202                                                       QLatin1String(memberName));
1203     QDBusMessagePrivate::setParametersValidated(message, true);
1204     message.setArguments(args);
1205     QDBusError error;
1206     DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1207     if (!msg) {
1208         qWarning("QDBusConnection: Could not emit signal %s.%s: %s", qPrintable(interface), memberName.constData(),
1209                  qPrintable(error.message()));
1210         lastError = error;
1211         return;
1212     }
1213
1214     //qDBusDebug() << "Emitting signal" << message;
1215     //qDBusDebug() << "for paths:";
1216     q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1217     huntAndEmit(connection, msg, obj, rootNode, isScriptable, isAdaptor);
1218     q_dbus_message_unref(msg);
1219 }
1220
1221 void QDBusConnectionPrivate::serviceOwnerChangedNoLock(const QString &name,
1222                                                        const QString &oldOwner, const QString &newOwner)
1223 {
1224     Q_UNUSED(oldOwner);
1225 //    QDBusWriteLocker locker(UpdateSignalHookOwnerAction, this);
1226     WatchedServicesHash::Iterator it = watchedServices.find(name);
1227     if (it == watchedServices.end())
1228         return;
1229     if (oldOwner != it->owner)
1230         qWarning("QDBusConnection: name '%s' had owner '%s' but we thought it was '%s'",
1231                  qPrintable(name), qPrintable(oldOwner), qPrintable(it->owner));
1232
1233     qDBusDebug() << this << "Updating name" << name << "from" << oldOwner << "to" << newOwner;
1234     it->owner = newOwner;
1235 }
1236
1237 int QDBusConnectionPrivate::findSlot(QObject* obj, const QByteArray &normalizedName,
1238                                      QVector<int> &params)
1239 {
1240     int midx = obj->metaObject()->indexOfMethod(normalizedName);
1241     if (midx == -1)
1242         return -1;
1243
1244     int inputCount = qDBusParametersForMethod(obj->metaObject()->method(midx), params);
1245     if ( inputCount == -1 || inputCount + 1 != params.count() )
1246         return -1;              // failed to parse or invalid arguments or output arguments
1247
1248     return midx;
1249 }
1250
1251 bool QDBusConnectionPrivate::prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
1252                                          const QString &service,
1253                                          const QString &path, const QString &interface, const QString &name,
1254                                          const QStringList &argMatch,
1255                                          QObject *receiver, const char *signal, int minMIdx,
1256                                          bool buildSignature)
1257 {
1258     QByteArray normalizedName = signal + 1;
1259     hook.midx = findSlot(receiver, signal + 1, hook.params);
1260     if (hook.midx == -1) {
1261         normalizedName = QMetaObject::normalizedSignature(signal + 1);
1262         hook.midx = findSlot(receiver, normalizedName, hook.params);
1263     }
1264     if (hook.midx < minMIdx) {
1265         if (hook.midx == -1)
1266         {}
1267         return false;
1268     }
1269
1270     hook.service = service;
1271     hook.path = path;
1272     hook.obj = receiver;
1273     hook.argumentMatch = argMatch;
1274
1275     // build the D-Bus signal name and signature
1276     // This should not happen for QDBusConnection::connect, use buildSignature here, since
1277     // QDBusConnection::connect passes false and everything else uses true
1278     QString mname = name;
1279     if (buildSignature && mname.isNull()) {
1280         normalizedName.truncate(normalizedName.indexOf('('));
1281         mname = QString::fromUtf8(normalizedName);
1282     }
1283     key = mname;
1284     key.reserve(interface.length() + 1 + mname.length());
1285     key += QLatin1Char(':');
1286     key += interface;
1287
1288     if (buildSignature) {
1289         hook.signature.clear();
1290         for (int i = 1; i < hook.params.count(); ++i)
1291             if (hook.params.at(i) != QDBusMetaTypeId::message)
1292                 hook.signature += QLatin1String( QDBusMetaType::typeToSignature( hook.params.at(i) ) );
1293     }
1294
1295     hook.matchRule = buildMatchRule(service, path, interface, mname, argMatch, hook.signature);
1296     return true;                // connect to this signal
1297 }
1298
1299 void QDBusConnectionPrivate::sendError(const QDBusMessage &msg, QDBusError::ErrorType code)
1300 {
1301     if (code == QDBusError::UnknownMethod) {
1302         QString interfaceMsg;
1303         if (msg.interface().isEmpty())
1304             interfaceMsg = QLatin1String("any interface");
1305         else
1306             interfaceMsg = QString::fromLatin1("interface '%1'").arg(msg.interface());
1307
1308         send(msg.createErrorReply(code,
1309                                   QString::fromLatin1("No such method '%1' in %2 at object path '%3' "
1310                                                       "(signature '%4')")
1311                                   .arg(msg.member(), interfaceMsg, msg.path(), msg.signature())));
1312     } else if (code == QDBusError::UnknownInterface) {
1313         send(msg.createErrorReply(QDBusError::UnknownInterface,
1314                                   QString::fromLatin1("No such interface '%1' at object path '%2'")
1315                                   .arg(msg.interface(), msg.path())));
1316     } else if (code == QDBusError::UnknownObject) {
1317         send(msg.createErrorReply(QDBusError::UnknownObject,
1318                                   QString::fromLatin1("No such object path '%1'").arg(msg.path())));
1319     }
1320 }
1321
1322 bool QDBusConnectionPrivate::activateInternalFilters(const ObjectTreeNode &node,
1323                                                      const QDBusMessage &msg)
1324 {
1325     // object may be null
1326     const QString interface = msg.interface();
1327
1328     if (interface.isEmpty() || interface == QLatin1String(DBUS_INTERFACE_INTROSPECTABLE)) {
1329         if (msg.member() == QLatin1String("Introspect") && msg.signature().isEmpty()) {
1330             //qDebug() << "QDBusConnectionPrivate::activateInternalFilters introspect" << msg.d_ptr->msg;
1331             QDBusMessage reply = msg.createReply(qDBusIntrospectObject(node, msg.path()));
1332             send(reply);
1333             return true;
1334         }
1335
1336         if (!interface.isEmpty()) {
1337             sendError(msg, QDBusError::UnknownMethod);
1338             return true;
1339         }
1340     }
1341
1342     if (node.obj && (interface.isEmpty() ||
1343                      interface == QLatin1String(DBUS_INTERFACE_PROPERTIES))) {
1344         //qDebug() << "QDBusConnectionPrivate::activateInternalFilters properties" << msg.d_ptr->msg;
1345         if (msg.member() == QLatin1String("Get") && msg.signature() == QLatin1String("ss")) {
1346             QDBusMessage reply = qDBusPropertyGet(node, msg);
1347             send(reply);
1348             return true;
1349         } else if (msg.member() == QLatin1String("Set") && msg.signature() == QLatin1String("ssv")) {
1350             QDBusMessage reply = qDBusPropertySet(node, msg);
1351             send(reply);
1352             return true;
1353         } else if (msg.member() == QLatin1String("GetAll") && msg.signature() == QLatin1String("s")) {
1354             QDBusMessage reply = qDBusPropertyGetAll(node, msg);
1355             send(reply);
1356             return true;
1357         }
1358
1359         if (!interface.isEmpty()) {
1360             sendError(msg, QDBusError::UnknownMethod);
1361             return true;
1362         }
1363     }
1364
1365     return false;
1366 }
1367
1368 void QDBusConnectionPrivate::activateObject(ObjectTreeNode &node, const QDBusMessage &msg,
1369                                             int pathStartPos)
1370 {
1371     // This is called by QDBusConnectionPrivate::handleObjectCall to place a call to a slot
1372     // on the object.
1373     //
1374     // The call is routed through the adaptor sub-objects if we have any
1375
1376     // object may be null
1377
1378     if (node.flags & QDBusConnectionPrivate::VirtualObject) {
1379         if (node.treeNode->handleMessage(msg, q(this))) {
1380             return;
1381         } else {
1382             if (activateInternalFilters(node, msg))
1383                 return;
1384         }
1385     }
1386
1387     if (pathStartPos != msg.path().length()) {
1388         node.flags &= ~QDBusConnection::ExportAllSignals;
1389         node.obj = findChildObject(&node, msg.path(), pathStartPos);
1390         if (!node.obj) {
1391             sendError(msg, QDBusError::UnknownObject);
1392             return;
1393         }
1394     }
1395
1396     QDBusAdaptorConnector *connector;
1397     if (node.flags & QDBusConnection::ExportAdaptors &&
1398         (connector = qDBusFindAdaptorConnector(node.obj))) {
1399         int newflags = node.flags | QDBusConnection::ExportAllSlots;
1400
1401         if (msg.interface().isEmpty()) {
1402             // place the call in all interfaces
1403             // let the first one that handles it to work
1404             QDBusAdaptorConnector::AdaptorMap::ConstIterator it =
1405                 connector->adaptors.constBegin();
1406             QDBusAdaptorConnector::AdaptorMap::ConstIterator end =
1407                 connector->adaptors.constEnd();
1408
1409             for ( ; it != end; ++it)
1410                 if (activateCall(it->adaptor, newflags, msg))
1411                     return;
1412         } else {
1413             // check if we have an interface matching the name that was asked:
1414             QDBusAdaptorConnector::AdaptorMap::ConstIterator it;
1415             it = qLowerBound(connector->adaptors.constBegin(), connector->adaptors.constEnd(),
1416                              msg.interface());
1417             if (it != connector->adaptors.constEnd() && msg.interface() == QLatin1String(it->interface)) {
1418                 if (!activateCall(it->adaptor, newflags, msg))
1419                     sendError(msg, QDBusError::UnknownMethod);
1420                 return;
1421             }
1422         }
1423     }
1424
1425     // no adaptors matched or were exported
1426     // try our standard filters
1427     if (activateInternalFilters(node, msg))
1428         return;                 // internal filters have already run or an error has been sent
1429
1430     // try the object itself:
1431     if (node.flags & (QDBusConnection::ExportScriptableSlots|QDBusConnection::ExportNonScriptableSlots) ||
1432         node.flags & (QDBusConnection::ExportScriptableInvokables|QDBusConnection::ExportNonScriptableInvokables)) {
1433         bool interfaceFound = true;
1434         if (!msg.interface().isEmpty())
1435             interfaceFound = qDBusInterfaceInObject(node.obj, msg.interface());
1436
1437         if (interfaceFound) {
1438             if (!activateCall(node.obj, node.flags, msg))
1439                 sendError(msg, QDBusError::UnknownMethod);
1440             return;
1441         }
1442     }
1443
1444     // nothing matched, send an error code
1445     if (msg.interface().isEmpty())
1446         sendError(msg, QDBusError::UnknownMethod);
1447     else
1448         sendError(msg, QDBusError::UnknownInterface);
1449 }
1450
1451 void QDBusConnectionPrivate::handleObjectCall(const QDBusMessage &msg)
1452 {
1453     // if the msg is external, we were called from inside doDispatch
1454     // that means the dispatchLock mutex is locked
1455     // must not call out to user code in that case
1456     //
1457     // however, if the message is internal, handleMessage was called
1458     // directly and no lock is in place. We can therefore call out to
1459     // user code, if necessary
1460     ObjectTreeNode result;
1461     int usedLength;
1462     QThread *objThread = 0;
1463     QSemaphore sem;
1464     bool semWait;
1465
1466     {
1467         QDBusReadLocker locker(HandleObjectCallAction, this);
1468         if (!findObject(&rootNode, msg.path(), usedLength, result)) {
1469             // qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
1470             sendError(msg, QDBusError::UnknownObject);
1471             return;
1472         }
1473
1474         if (!result.obj) {
1475             // no object -> no threading issues
1476             // it's either going to be an error, or an internal filter
1477             activateObject(result, msg, usedLength);
1478             return;
1479         }
1480
1481         objThread = result.obj->thread();
1482         if (!objThread) {
1483             send(msg.createErrorReply(QDBusError::InternalError,
1484                                       QString::fromLatin1("Object '%1' (at path '%2')"
1485                                                           " has no thread. Cannot deliver message.")
1486                                       .arg(result.obj->objectName(), msg.path())));
1487             return;
1488         }
1489
1490         if (!QDBusMessagePrivate::isLocal(msg)) {
1491             // external incoming message
1492             // post it and forget
1493             postEventToThread(HandleObjectCallPostEventAction, result.obj,
1494                               new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1495                                                            usedLength, msg));
1496             return;
1497         } else if (objThread != QThread::currentThread()) {
1498             // synchronize with other thread
1499             postEventToThread(HandleObjectCallPostEventAction, result.obj,
1500                               new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1501                                                            usedLength, msg, &sem));
1502             semWait = true;
1503         } else {
1504             semWait = false;
1505         }
1506     } // release the lock
1507
1508     if (semWait)
1509         SEM_ACQUIRE(HandleObjectCallSemaphoreAction, sem);
1510     else
1511         activateObject(result, msg, usedLength);
1512 }
1513
1514 QDBusActivateObjectEvent::~QDBusActivateObjectEvent()
1515 {
1516     if (!handled) {
1517         // we're being destroyed without delivering
1518         // it means the object was deleted between posting and delivering
1519         QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1520         that->sendError(message, QDBusError::UnknownObject);
1521     }
1522
1523     // semaphore releasing happens in ~QMetaCallEvent
1524 }
1525
1526 void QDBusActivateObjectEvent::placeMetaCall(QObject *)
1527 {
1528     QDBusConnectionPrivate *that = QDBusConnectionPrivate::d(connection);
1529
1530     QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1531                                         QDBusLockerBase::BeforeDeliver, that);
1532     that->activateObject(node, message, pathStartPos);
1533     QDBusLockerBase::reportThreadAction(HandleObjectCallPostEventAction,
1534                                         QDBusLockerBase::AfterDeliver, that);
1535
1536     handled = true;
1537 }
1538
1539 void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1540 {
1541     SignalHookHash::const_iterator it = signalHooks.find(key);
1542     SignalHookHash::const_iterator end = signalHooks.constEnd();
1543     //qDebug("looking for: %s", path.toLocal8Bit().constData());
1544     //qDBusDebug() << signalHooks.keys();
1545     for ( ; it != end && it.key() == key; ++it) {
1546         const SignalHook &hook = it.value();
1547         if (!hook.service.isEmpty()) {
1548             const QString owner =
1549                     shouldWatchService(hook.service) ?
1550                     watchedServices.value(hook.service).owner :
1551                     hook.service;
1552             if (owner != msg.service())
1553                 continue;
1554         }
1555         if (!hook.path.isEmpty() && hook.path != msg.path())
1556             continue;
1557         if (!hook.signature.isEmpty() && hook.signature != msg.signature())
1558             continue;
1559         if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1560             continue;
1561         if (!hook.argumentMatch.isEmpty()) {
1562             const QVariantList arguments = msg.arguments();
1563             if (hook.argumentMatch.size() > arguments.size())
1564                 continue;
1565
1566             bool matched = true;
1567             for (int i = 0; i < hook.argumentMatch.size(); ++i) {
1568                 const QString &param = hook.argumentMatch.at(i);
1569                 if (param.isNull())
1570                     continue;   // don't try to match against this
1571                 if (param == arguments.at(i).toString())
1572                     continue;   // matched
1573                 matched = false;
1574                 break;
1575             }
1576             if (!matched)
1577                 continue;
1578         }
1579
1580         activateSignal(hook, msg);
1581     }
1582 }
1583
1584 void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1585 {
1586     // We call handlesignal(QString, QDBusMessage) three times:
1587     //  one with member:interface
1588     //  one with member:
1589     //  one with :interface
1590     // This allows us to match signals with wildcards on member or interface
1591     // (but not both)
1592
1593     QString key = msg.member();
1594     key.reserve(key.length() + 1 + msg.interface().length());
1595     key += QLatin1Char(':');
1596     key += msg.interface();
1597
1598     QDBusReadLocker locker(HandleSignalAction, this);
1599     handleSignal(key, msg);                  // one try
1600
1601     key.truncate(msg.member().length() + 1); // keep the ':'
1602     handleSignal(key, msg);                  // second try
1603
1604     key = QLatin1Char(':');
1605     key += msg.interface();
1606     handleSignal(key, msg);                  // third try
1607 }
1608
1609 static dbus_int32_t server_slot = -1;
1610
1611 void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
1612 {
1613     if (!s) {
1614         handleError(error);
1615         return;
1616     }
1617
1618     server = s;
1619     mode = ServerMode;
1620
1621     dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
1622     if (data_allocated && server_slot < 0)
1623         return;
1624
1625     dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
1626                                                                       qDBusAddWatch,
1627                                                                       qDBusRemoveWatch,
1628                                                                       qDBusToggleWatch,
1629                                                                       this, 0);
1630     //qDebug() << "watch_functions_set" << watch_functions_set;
1631     Q_UNUSED(watch_functions_set);
1632
1633     dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
1634                                                                        qDBusAddTimeout,
1635                                                                        qDBusRemoveTimeout,
1636                                                                        qDBusToggleTimeout,
1637                                                                        this, 0);
1638     //qDebug() << "time_functions_set" << time_functions_set;
1639     Q_UNUSED(time_functions_set);
1640
1641     q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1642
1643     dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
1644     //qDebug() << "data_set" << data_set;
1645     Q_UNUSED(data_set);
1646 }
1647
1648 void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
1649 {
1650     if (!c) {
1651         handleError(error);
1652         return;
1653     }
1654
1655     connection = c;
1656     mode = PeerMode;
1657
1658     q_dbus_connection_set_exit_on_disconnect(connection, false);
1659     q_dbus_connection_set_watch_functions(connection,
1660                                         qDBusAddWatch,
1661                                         qDBusRemoveWatch,
1662                                         qDBusToggleWatch,
1663                                         this, 0);
1664     q_dbus_connection_set_timeout_functions(connection,
1665                                           qDBusAddTimeout,
1666                                           qDBusRemoveTimeout,
1667                                           qDBusToggleTimeout,
1668                                           this, 0);
1669     q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1670     q_dbus_connection_add_filter(connection,
1671                                qDBusSignalFilter,
1672                                this, 0);
1673
1674     QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1675 }
1676
1677 static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnection *connection)
1678 {
1679     QDBusConnection::ConnectionCapabilities result = 0;
1680
1681 #if defined(QT_LINKED_LIBDBUS) && DBUS_VERSION < 0x010400
1682     // no capabilities are possible
1683 #else
1684 # if !defined(QT_LINKED_LIBDBUS)
1685     // run-time check if the next functions are available
1686     int major, minor, micro;
1687     q_dbus_get_version(&major, &minor, &micro);
1688     if (major == 1 && minor < 4)
1689         return result;
1690 # endif
1691
1692 #ifndef DBUS_TYPE_UNIX_FD
1693 # define DBUS_TYPE_UNIX_FD int('h')
1694 #endif
1695     if (q_dbus_connection_can_send_type(connection, DBUS_TYPE_UNIX_FD))
1696         result |= QDBusConnection::UnixFileDescriptorPassing;
1697 #endif
1698
1699     return result;
1700 }
1701
1702 void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
1703 {
1704     if (!dbc) {
1705         handleError(error);
1706         return;
1707     }
1708
1709     connection = dbc;
1710     mode = ClientMode;
1711
1712     const char *service = q_dbus_bus_get_unique_name(connection);
1713     Q_ASSERT(service);
1714     baseService = QString::fromUtf8(service);
1715     capabilities = connectionCapabilies(connection);
1716
1717     q_dbus_connection_set_exit_on_disconnect(connection, false);
1718     q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1719                                           qDBusToggleWatch, this, 0);
1720     q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1721                                             qDBusToggleTimeout, this, 0);
1722     q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1723     q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1724
1725     // Initialize the hooks for the NameAcquired and NameLost signals
1726     // we don't use connectSignal here because we don't need the rules to be sent to the bus
1727     // the bus will always send us these two signals
1728     SignalHook hook;
1729     hook.service = dbusServiceString();
1730     hook.path.clear(); // no matching
1731     hook.obj = this;
1732     hook.params << QMetaType::Void << QVariant::String; // both functions take a QString as parameter and return void
1733
1734     hook.midx = staticMetaObject.indexOfSlot("registerServiceNoLock(QString)");
1735     Q_ASSERT(hook.midx != -1);
1736     signalHooks.insert(QLatin1String("NameAcquired:" DBUS_INTERFACE_DBUS), hook);
1737
1738     hook.midx = staticMetaObject.indexOfSlot("unregisterServiceNoLock(QString)");
1739     Q_ASSERT(hook.midx != -1);
1740     signalHooks.insert(QLatin1String("NameLost:" DBUS_INTERFACE_DBUS), hook);
1741
1742     qDBusDebug() << this << ": connected successfully";
1743
1744     // schedule a dispatch:
1745     QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1746 }
1747
1748 extern "C"{
1749 static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1750 {
1751     QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
1752     Q_ASSERT(call->pending == pending);
1753     Q_UNUSED(pending);
1754     QDBusConnectionPrivate::processFinishedCall(call);
1755 }
1756 }
1757
1758 void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
1759 {
1760     Q_ASSERT(pcall->pending);
1761     Q_ASSERT(!pcall->autoDelete);
1762     //Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
1763
1764     if (pcall->waitingForFinished) {
1765         // another thread is already waiting
1766         pcall->waitForFinishedCondition.wait(&pcall->mutex);
1767     } else {
1768         pcall->waitingForFinished = true;
1769         pcall->mutex.unlock();
1770
1771         {
1772             QDBusDispatchLocker locker(PendingCallBlockAction, this);
1773             q_dbus_pending_call_block(pcall->pending);
1774             // QDBusConnectionPrivate::processFinishedCall() is called automatically
1775         }
1776         pcall->mutex.lock();
1777     }
1778 }
1779
1780 void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
1781 {
1782     QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1783
1784     QMutexLocker locker(&call->mutex);
1785
1786     QDBusMessage &msg = call->replyMessage;
1787     if (call->pending) {
1788         // decode the message
1789         DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
1790         msg = QDBusMessagePrivate::fromDBusMessage(reply, connection->capabilities);
1791         q_dbus_message_unref(reply);
1792     }
1793     qDBusDebug() << connection << "got message reply (async):" << msg;
1794
1795     // Check if the reply has the expected signature
1796     call->checkReceivedSignature();
1797
1798     if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
1799         // Deliver the return values of a remote function call.
1800         //
1801         // There is only one connection and it is specified by idx
1802         // The slot must have the same parameter types that the message does
1803         // The slot may have less parameters than the message
1804         // The slot may optionally have one final parameter that is QDBusMessage
1805         // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1806
1807         QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
1808                                                  call->metaTypes, msg);
1809         if (e)
1810             connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
1811         else
1812             qDBusDebug() << "Deliver failed!";
1813     }
1814
1815     if (call->pending)
1816         q_dbus_pending_call_unref(call->pending);
1817     call->pending = 0;
1818
1819     locker.unlock();
1820
1821     // Are there any watchers?
1822     if (call->watcherHelper)
1823         call->watcherHelper->emitSignals(msg, call->sentMessage);
1824
1825     if (msg.type() == QDBusMessage::ErrorMessage)
1826         emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
1827
1828     if (call->autoDelete) {
1829         Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
1830         delete call;
1831     }
1832 }
1833
1834 int QDBusConnectionPrivate::send(const QDBusMessage& message)
1835 {
1836     if (QDBusMessagePrivate::isLocal(message))
1837         return -1;              // don't send; the reply will be retrieved by the caller
1838                                 // through the d_ptr->localReply link
1839
1840     QDBusError error;
1841     DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1842     if (!msg) {
1843         if (message.type() == QDBusMessage::MethodCallMessage)
1844             qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1845                      qPrintable(message.service()), qPrintable(message.path()),
1846                      qPrintable(message.interface()), qPrintable(message.member()),
1847                      qPrintable(error.message()));
1848         else if (message.type() == QDBusMessage::SignalMessage)
1849             qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
1850                      qPrintable(message.path()), qPrintable(message.interface()),
1851                      qPrintable(message.member()),
1852                      qPrintable(error.message()));
1853         else
1854             qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
1855                      message.type() == QDBusMessage::ReplyMessage ? "reply" :
1856                      message.type() == QDBusMessage::ErrorMessage ? "error" :
1857                      "invalid", qPrintable(message.service()),
1858                      qPrintable(error.message()));
1859         lastError = error;
1860         return 0;
1861     }
1862
1863     q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1864
1865     qDBusDebug() << this << "sending message (no reply):" << message;
1866     checkThread();
1867     bool isOk = q_dbus_connection_send(connection, msg, 0);
1868     int serial = 0;
1869     if (isOk)
1870         serial = q_dbus_message_get_serial(msg);
1871
1872     q_dbus_message_unref(msg);
1873     return serial;
1874 }
1875
1876 QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1877                                                    int sendMode, int timeout)
1878 {
1879     checkThread();
1880     if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
1881          && isServiceRegisteredByThread(message.service()))
1882         // special case for synchronous local calls
1883         return sendWithReplyLocal(message);
1884
1885     if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
1886         QDBusError err;
1887         DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &err);
1888         if (!msg) {
1889             qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1890                      qPrintable(message.service()), qPrintable(message.path()),
1891                      qPrintable(message.interface()), qPrintable(message.member()),
1892                      qPrintable(err.message()));
1893             lastError = err;
1894             return QDBusMessage::createError(err);
1895         }
1896
1897         qDBusDebug() << this << "sending message (blocking):" << message;
1898         QDBusErrorInternal error;
1899         DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
1900
1901         q_dbus_message_unref(msg);
1902
1903         if (!!error) {
1904             lastError = err = error;
1905             return QDBusMessage::createError(err);
1906         }
1907
1908         QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply, capabilities);
1909         q_dbus_message_unref(reply);
1910         qDBusDebug() << this << "got message reply (blocking):" << amsg;
1911
1912         return amsg;
1913     } else { // use the event loop
1914         QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1915         Q_ASSERT(pcall);
1916
1917         if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
1918             pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
1919             QEventLoop loop;
1920             loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
1921             loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
1922
1923             // enter the event loop and wait for a reply
1924             loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1925         }
1926
1927         QDBusMessage reply = pcall->replyMessage;
1928         lastError = QDBusError(reply);      // set or clear error
1929
1930         delete pcall;
1931         return reply;
1932     }
1933 }
1934
1935 QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
1936 {
1937     qDBusDebug() << this << "sending message via local-loop:" << message;
1938
1939     QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
1940     bool handled = handleMessage(localCallMsg);
1941
1942     if (!handled) {
1943         QString interface = message.interface();
1944         if (interface.isEmpty())
1945             interface = QLatin1String("<no-interface>");
1946         return QDBusMessage::createError(QDBusError::InternalError,
1947                                          QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
1948                                          .arg(interface, message.member(),
1949                                               message.path(), message.signature()));
1950     }
1951
1952     // if the message was handled, there might be a reply
1953     QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
1954     if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
1955         qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
1956                  "on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
1957                  qPrintable(message.signature()));
1958         return QDBusMessage::createError(
1959             QDBusError(QDBusError::InternalError,
1960                        QLatin1String("local-loop message cannot have delayed replies")));
1961     }
1962
1963     // there is a reply
1964     qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
1965     return localReplyMsg;
1966 }
1967
1968 QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
1969                                                                     int timeout)
1970 {
1971     if (isServiceRegisteredByThread(message.service())) {
1972         // special case for local calls
1973         QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1974         pcall->replyMessage = sendWithReplyLocal(message);
1975
1976         return pcall;
1977     }
1978
1979     checkThread();
1980     QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1981     pcall->ref.store(0);
1982
1983     QDBusError error;
1984     DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, capabilities, &error);
1985     if (!msg) {
1986         qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1987                  qPrintable(message.service()), qPrintable(message.path()),
1988                  qPrintable(message.interface()), qPrintable(message.member()),
1989                  qPrintable(error.message()));
1990         pcall->replyMessage = QDBusMessage::createError(error);
1991         lastError = error;
1992         return pcall;
1993     }
1994
1995     qDBusDebug() << this << "sending message (async):" << message;
1996     DBusPendingCall *pending = 0;
1997
1998     QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
1999     if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
2000         if (pending) {
2001             q_dbus_message_unref(msg);
2002
2003             pcall->pending = pending;
2004             q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
2005
2006             return pcall;
2007         } else {
2008             // we're probably disconnected at this point
2009             lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
2010         }
2011     } else {
2012         lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
2013     }
2014
2015     q_dbus_message_unref(msg);
2016     pcall->replyMessage = QDBusMessage::createError(error);
2017     return pcall;
2018 }
2019
2020 int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
2021                                                const char *returnMethod, const char *errorMethod,
2022                                                int timeout)
2023 {
2024     QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
2025     Q_ASSERT(pcall);
2026
2027     // has it already finished with success (dispatched locally)?
2028     if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
2029         pcall->setReplyCallback(receiver, returnMethod);
2030         processFinishedCall(pcall);
2031         delete pcall;
2032         return 1;
2033     }
2034
2035     // either it hasn't finished or it has finished with error
2036     if (errorMethod) {
2037         pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
2038         connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
2039                 Qt::QueuedConnection);
2040         pcall->watcherHelper->moveToThread(thread());
2041     }
2042
2043     // has it already finished and is an error reply message?
2044     if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
2045         processFinishedCall(pcall);
2046         delete pcall;
2047         return 1;
2048     }
2049
2050     pcall->autoDelete = true;
2051     pcall->ref.ref();
2052     pcall->setReplyCallback(receiver, returnMethod);
2053
2054     return 1;
2055 }
2056
2057 bool QDBusConnectionPrivate::connectSignal(const QString &service,
2058                                            const QString &path, const QString &interface, const QString &name,
2059                                            const QStringList &argumentMatch, const QString &signature,
2060                                            QObject *receiver, const char *slot)
2061 {
2062     // check the slot
2063     QDBusConnectionPrivate::SignalHook hook;
2064     QString key;
2065     QString name2 = name;
2066     if (name2.isNull())
2067         name2.detach();
2068
2069     hook.signature = signature;
2070     if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2071         return false;           // don't connect
2072
2073     // avoid duplicating:
2074     QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.find(key);
2075     QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
2076     for ( ; it != end && it.key() == key; ++it) {
2077         const QDBusConnectionPrivate::SignalHook &entry = it.value();
2078         if (entry.service == hook.service &&
2079             entry.path == hook.path &&
2080             entry.signature == hook.signature &&
2081             entry.obj == hook.obj &&
2082             entry.midx == hook.midx &&
2083             entry.argumentMatch == hook.argumentMatch) {
2084             // no need to compare the parameters if it's the same slot
2085             return true;        // already there
2086         }
2087     }
2088
2089     connectSignal(key, hook);
2090     return true;
2091 }
2092
2093 void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
2094 {
2095     signalHooks.insertMulti(key, hook);
2096     connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2097             Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
2098
2099     MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
2100
2101     if (it != matchRefCounts.end()) { // Match already present
2102         it.value() = it.value() + 1;
2103         return;
2104     }
2105
2106     matchRefCounts.insert(hook.matchRule, 1);
2107
2108     if (connection) {
2109         if (mode != QDBusConnectionPrivate::PeerMode) {
2110             qDBusDebug("Adding rule: %s", hook.matchRule.constData());
2111             q_dbus_bus_add_match(connection, hook.matchRule, NULL);
2112
2113             // Successfully connected the signal
2114             // Do we need to watch for this name?
2115             if (shouldWatchService(hook.service)) {
2116                 WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
2117                 if (++data.refcount == 1) {
2118                     // we need to watch for this service changing
2119                     connectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2120                                   QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2121                                   this, SLOT(serviceOwnerChangedNoLock(QString,QString,QString)));
2122                     data.owner = getNameOwnerNoCache(hook.service);
2123                     qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
2124                                  << data.owner << ")";
2125                 }
2126             }
2127         }
2128     }
2129 }
2130
2131 bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
2132                                               const QString &path, const QString &interface, const QString &name,
2133                                               const QStringList &argumentMatch, const QString &signature,
2134                                               QObject *receiver, const char *slot)
2135 {
2136     // check the slot
2137     QDBusConnectionPrivate::SignalHook hook;
2138     QString key;
2139     QString name2 = name;
2140     if (name2.isNull())
2141         name2.detach();
2142
2143     hook.signature = signature;
2144     if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2145         return false;           // don't disconnect
2146
2147     // avoid duplicating:
2148     QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
2149     QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
2150     for ( ; it != end && it.key() == key; ++it) {
2151         const QDBusConnectionPrivate::SignalHook &entry = it.value();
2152         if (entry.service == hook.service &&
2153             entry.path == hook.path &&
2154             entry.signature == hook.signature &&
2155             entry.obj == hook.obj &&
2156             entry.midx == hook.midx &&
2157             entry.argumentMatch == hook.argumentMatch) {
2158             // no need to compare the parameters if it's the same slot
2159             disconnectSignal(it);
2160             return true;        // it was there
2161         }
2162     }
2163
2164     // the slot was not found
2165     return false;
2166 }
2167
2168 QDBusConnectionPrivate::SignalHookHash::Iterator
2169 QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
2170 {
2171     const SignalHook &hook = it.value();
2172
2173     bool erase = false;
2174     MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
2175     if (i == matchRefCounts.end()) {
2176         qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
2177     } else {
2178         if (i.value() == 1) {
2179             erase = true;
2180             matchRefCounts.erase(i);
2181         }
2182         else {
2183             i.value() = i.value() - 1;
2184         }
2185     }
2186
2187     // we don't care about errors here
2188     if (connection && erase) {
2189         if (mode != QDBusConnectionPrivate::PeerMode) {
2190             qDBusDebug("Removing rule: %s", hook.matchRule.constData());
2191             q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
2192
2193             // Successfully disconnected the signal
2194             // Were we watching for this name?
2195             WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
2196             if (sit != watchedServices.end()) {
2197                 if (--sit.value().refcount == 0) {
2198                     watchedServices.erase(sit);
2199                     disconnectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2200                                   QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2201                                   this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
2202                 }
2203             }
2204         }
2205
2206     }
2207
2208     return signalHooks.erase(it);
2209 }
2210
2211 void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
2212 {
2213     connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2214             Qt::DirectConnection);
2215
2216     if (node->flags & (QDBusConnection::ExportAdaptors
2217                        | QDBusConnection::ExportScriptableSignals
2218                        | QDBusConnection::ExportNonScriptableSignals)) {
2219         QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
2220
2221         if (node->flags & (QDBusConnection::ExportScriptableSignals
2222                            | QDBusConnection::ExportNonScriptableSignals)) {
2223             connector->disconnectAllSignals(node->obj);
2224             connector->connectAllSignals(node->obj);
2225         }
2226
2227         // disconnect and reconnect to avoid duplicates
2228         connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2229                               this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
2230         connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2231                 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2232                 Qt::DirectConnection);
2233     }
2234 }
2235
2236 void QDBusConnectionPrivate::connectRelay(const QString &service,
2237                                           const QString &path, const QString &interface,
2238                                           QDBusAbstractInterface *receiver,
2239                                           const QMetaMethod &signal)
2240 {
2241     // this function is called by QDBusAbstractInterface when one of its signals is connected
2242     // we set up a relay from D-Bus into it
2243     SignalHook hook;
2244     QString key;
2245
2246     QByteArray sig;
2247     sig.append(QSIGNAL_CODE + '0');
2248     sig.append(signal.methodSignature());
2249     if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, sig,
2250                      QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2251         return;                 // don't connect
2252
2253     // add it to our list:
2254     QDBusWriteLocker locker(ConnectRelayAction, this);
2255     SignalHookHash::ConstIterator it = signalHooks.find(key);
2256     SignalHookHash::ConstIterator end = signalHooks.constEnd();
2257     for ( ; it != end && it.key() == key; ++it) {
2258         const SignalHook &entry = it.value();
2259         if (entry.service == hook.service &&
2260             entry.path == hook.path &&
2261             entry.signature == hook.signature &&
2262             entry.obj == hook.obj &&
2263             entry.midx == hook.midx)
2264             return;             // already there, no need to re-add
2265     }
2266
2267     connectSignal(key, hook);
2268 }
2269
2270 void QDBusConnectionPrivate::disconnectRelay(const QString &service,
2271                                              const QString &path, const QString &interface,
2272                                              QDBusAbstractInterface *receiver,
2273                                              const QMetaMethod &signal)
2274 {
2275     // this function is called by QDBusAbstractInterface when one of its signals is disconnected
2276     // we remove relay from D-Bus into it
2277     SignalHook hook;
2278     QString key;
2279
2280     QByteArray sig;
2281     sig.append(QSIGNAL_CODE + '0');
2282     sig.append(signal.methodSignature());
2283     if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, sig,
2284                      QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2285         return;                 // don't connect
2286
2287     // remove it from our list:
2288     QDBusWriteLocker locker(DisconnectRelayAction, this);
2289     SignalHookHash::Iterator it = signalHooks.find(key);
2290     SignalHookHash::Iterator end = signalHooks.end();
2291     for ( ; it != end && it.key() == key; ++it) {
2292         const SignalHook &entry = it.value();
2293         if (entry.service == hook.service &&
2294             entry.path == hook.path &&
2295             entry.signature == hook.signature &&
2296             entry.obj == hook.obj &&
2297             entry.midx == hook.midx) {
2298             // found it
2299             disconnectSignal(it);
2300             return;
2301         }
2302     }
2303
2304     qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
2305 }
2306
2307 QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
2308 {
2309     if (QDBusUtil::isValidUniqueConnectionName(serviceName))
2310         return serviceName;
2311     if (!connection)
2312         return QString();
2313
2314     {
2315         // acquire a read lock for the cache
2316         QReadLocker locker(&lock);
2317         WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
2318         if (it != watchedServices.constEnd())
2319             return it->owner;
2320     }
2321
2322     // not cached
2323     return getNameOwnerNoCache(serviceName);
2324 }
2325
2326 QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
2327 {
2328     QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2329             QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2330             QLatin1String("GetNameOwner"));
2331     QDBusMessagePrivate::setParametersValidated(msg, true);
2332     msg << serviceName;
2333     QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2334     if (reply.type() == QDBusMessage::ReplyMessage)
2335         return reply.arguments().at(0).toString();
2336     return QString();
2337 }
2338
2339 QDBusMetaObject *
2340 QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
2341                                        const QString &interface, QDBusError &error)
2342 {
2343     // service must be a unique connection name
2344     if (!interface.isEmpty()) {
2345         QDBusReadLocker locker(FindMetaObject1Action, this);
2346         QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
2347         if (mo)
2348             return mo;
2349     }
2350
2351     // introspect the target object
2352     QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
2353                                                 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
2354                                                 QLatin1String("Introspect"));
2355     QDBusMessagePrivate::setParametersValidated(msg, true);
2356
2357     QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2358
2359     // it doesn't exist yet, we have to create it
2360     QDBusWriteLocker locker(FindMetaObject2Action, this);
2361     QDBusMetaObject *mo = 0;
2362     if (!interface.isEmpty())
2363         mo = cachedMetaObjects.value(interface, 0);
2364     if (mo)
2365         // maybe it got created when we switched from read to write lock
2366         return mo;
2367
2368     QString xml;
2369     if (reply.type() == QDBusMessage::ReplyMessage) {
2370         if (reply.signature() == QLatin1String("s"))
2371             // fetch the XML description
2372             xml = reply.arguments().at(0).toString();
2373     } else {
2374         error = QDBusError(reply);
2375         lastError = error;
2376         if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
2377             return 0; // error
2378     }
2379
2380     // release the lock and return
2381     QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
2382                                                                 cachedMetaObjects, error);
2383     lastError = error;
2384     return result;
2385 }
2386
2387 void QDBusConnectionPrivate::registerService(const QString &serviceName)
2388 {
2389     QDBusWriteLocker locker(RegisterServiceAction, this);
2390     registerServiceNoLock(serviceName);
2391 }
2392
2393 void QDBusConnectionPrivate::registerServiceNoLock(const QString &serviceName)
2394 {
2395     serviceNames.append(serviceName);
2396 }
2397
2398 void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
2399 {
2400     QDBusWriteLocker locker(UnregisterServiceAction, this);
2401     unregisterServiceNoLock(serviceName);
2402 }
2403
2404 void QDBusConnectionPrivate::unregisterServiceNoLock(const QString &serviceName)
2405 {
2406     serviceNames.removeAll(serviceName);
2407 }
2408
2409 bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
2410 {
2411     if (!serviceName.isEmpty() && serviceName == baseService)
2412         return true;
2413     QStringList copy = serviceNames;
2414     return copy.contains(serviceName);
2415 }
2416
2417 void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
2418 {
2419     QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
2420     QCoreApplication::postEvent(object, ev);
2421     QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
2422 }
2423
2424 QT_END_NAMESPACE
2425
2426 #endif // QT_NO_DBUS