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