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