source: trunk/src/dbus/qdbusintegrator.cpp@ 769

Last change on this file since 769 was 769, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.3 sources from branches/vendor/nokia/qt.

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