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