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