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