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

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

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

File size: 89.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
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 [email protected].
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
69QT_BEGIN_NAMESPACE
70
71static bool isDebugging;
72#define qDBusDebug if (!::isDebugging); else qDebug
73
74Q_GLOBAL_STATIC_WITH_ARGS(const QString, orgFreedesktopDBusString, (QLatin1String(DBUS_SERVICE_DBUS)))
75
76static inline QString dbusServiceString()
77{ return *orgFreedesktopDBusString(); }
78static 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
85static 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
95static 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
110Q_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}
129Q_AUTOTEST_EXPORT qdbusThreadDebugFunc qdbusThreadDebug = 0;
130#endif
131
132typedef void (*QDBusSpyHook)(const QDBusMessage&);
133typedef QVarLengthArray<QDBusSpyHook, 4> QDBusSpyHookList;
134Q_GLOBAL_STATIC(QDBusSpyHookList, qDBusSpyHookList)
135
136extern "C" {
137
138 // libdbus-1 callbacks
139
140static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms);
141static 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
167static 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
179static 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
222static 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
233static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd);
234static 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
257static 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
285static 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
317static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd);
318static 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
337static 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
359static 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
378static 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 = new QDBusConnectionPrivate;
388
389 // setConnection does the error handling for us
390 QDBusErrorInternal error;
391 d->setPeer(connection, error);
392
393 QDBusConnection retval = QDBusConnectionPrivate::q(d);
394 d->setBusService(retval);
395
396 //d->name = QString::number(reinterpret_cast<int>(d));
397 //d->setConnection(d->name, d);
398
399 // make QDBusServer emit the newConnection signal
400 QDBusConnectionPrivate *server_d = static_cast<QDBusConnectionPrivate *>(data);
401 server_d->serverConnection(retval);
402}
403
404} // extern "C"
405
406static QByteArray buildMatchRule(const QString &service,
407 const QString &objectPath, const QString &interface,
408 const QString &member, const QStringList &argMatch, const QString & /*signature*/)
409{
410 QString result = QLatin1String("type='signal',");
411 QString keyValue = QLatin1String("%1='%2',");
412
413 if (!service.isEmpty())
414 result += keyValue.arg(QLatin1String("sender"), service);
415 if (!objectPath.isEmpty())
416 result += keyValue.arg(QLatin1String("path"), objectPath);
417 if (!interface.isEmpty())
418 result += keyValue.arg(QLatin1String("interface"), interface);
419 if (!member.isEmpty())
420 result += keyValue.arg(QLatin1String("member"), member);
421
422 // add the argument string-matching now
423 if (!argMatch.isEmpty()) {
424 keyValue = QLatin1String("arg%1='%2',");
425 for (int i = 0; i < argMatch.count(); ++i)
426 if (!argMatch.at(i).isNull())
427 result += keyValue.arg(i).arg(argMatch.at(i));
428 }
429
430 result.chop(1); // remove ending comma
431 return result.toLatin1();
432}
433
434static bool findObject(const QDBusConnectionPrivate::ObjectTreeNode *root,
435 const QString &fullpath, int &usedLength,
436 QDBusConnectionPrivate::ObjectTreeNode &result)
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
474static 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
517static bool shouldWatchService(const QString &service)
518{
519 return !service.isEmpty() && !service.startsWith(QLatin1Char(':'));
520}
521
522extern Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook);
523void qDBusAddSpyHook(QDBusSpyHook hook)
524{
525 qDBusSpyHookList()->append(hook);
526}
527
528extern "C" {
529static DBusHandlerResult
530qDBusSignalFilter(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);
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
547bool 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 return true;
562 break;
563 case QDBusMessage::MethodCallMessage:
564 handleObjectCall(amsg);
565 return true;
566 case QDBusMessage::ReplyMessage:
567 case QDBusMessage::ErrorMessage:
568 case QDBusMessage::InvalidMessage:
569 return false; // we don't handle those here
570 }
571
572 return false;
573}
574
575static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode &haystack)
576{
577 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it = haystack.children.begin();
578 QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator end = haystack.children.end();
579 for ( ; it != end; ++it)
580 huntAndDestroy(needle, *it);
581
582 if (needle == haystack.obj) {
583 haystack.obj = 0;
584 haystack.flags = 0;
585 }
586}
587
588static void huntAndEmit(DBusConnection *connection, DBusMessage *msg,
589 QObject *needle, const QDBusConnectionPrivate::ObjectTreeNode &haystack,
590 bool isScriptable, bool isAdaptor, const QString &path = QString())
591{
592 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it = haystack.children.constBegin();
593 QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end = haystack.children.constEnd();
594 for ( ; it != end; ++it)
595 huntAndEmit(connection, msg, needle, *it, isScriptable, isAdaptor, path + QLatin1Char('/') + it->name);
596
597 if (needle == haystack.obj) {
598 // is this a signal we should relay?
599 if (isAdaptor && (haystack.flags & QDBusConnection::ExportAdaptors) == 0)
600 return; // no: it comes from an adaptor and we're not exporting adaptors
601 else if (!isAdaptor) {
602 int mask = isScriptable
603 ? QDBusConnection::ExportScriptableSignals
604 : QDBusConnection::ExportNonScriptableSignals;
605 if ((haystack.flags & mask) == 0)
606 return; // signal was not exported
607 }
608
609 QByteArray p = path.toLatin1();
610 if (p.isEmpty())
611 p = "/";
612 qDBusDebug() << QThread::currentThread() << "emitting signal at" << p;
613 DBusMessage *msg2 = q_dbus_message_copy(msg);
614 q_dbus_message_set_path(msg2, p);
615 q_dbus_connection_send(connection, msg2, 0);
616 q_dbus_message_unref(msg2);
617 }
618}
619
620static int findSlot(const QMetaObject *mo, const QByteArray &name, int flags,
621 const QString &signature_, QList<int>& metaTypes)
622{
623 QByteArray msgSignature = signature_.toLatin1();
624
625 for (int idx = mo->methodCount() - 1 ; idx >= QObject::staticMetaObject.methodCount(); --idx) {
626 QMetaMethod mm = mo->method(idx);
627
628 // check access:
629 if (mm.access() != QMetaMethod::Public)
630 continue;
631
632 // check type:
633 if (mm.methodType() != QMetaMethod::Slot && mm.methodType() != QMetaMethod::Method)
634 continue;
635
636 // check name:
637 QByteArray slotname = mm.signature();
638 int paren = slotname.indexOf('(');
639 if (paren != name.length() || !slotname.startsWith(name))
640 continue;
641
642 int returnType = qDBusNameToTypeId(mm.typeName());
643 bool isAsync = qDBusCheckAsyncTag(mm.tag());
644 bool isScriptable = mm.attributes() & QMetaMethod::Scriptable;
645
646 // consistency check:
647 if (isAsync && returnType != QMetaType::Void)
648 continue;
649
650 int inputCount = qDBusParametersForMethod(mm, metaTypes);
651 if (inputCount == -1)
652 continue; // problem parsing
653
654 metaTypes[0] = returnType;
655 bool hasMessage = false;
656 if (inputCount > 0 &&
657 metaTypes.at(inputCount) == QDBusMetaTypeId::message) {
658 // "no input parameters" is allowed as long as the message meta type is there
659 hasMessage = true;
660 --inputCount;
661 }
662
663 // try to match the parameters
664 int i;
665 QByteArray reconstructedSignature;
666 for (i = 1; i <= inputCount; ++i) {
667 const char *typeSignature = QDBusMetaType::typeToSignature( metaTypes.at(i) );
668 if (!typeSignature)
669 break; // invalid
670
671 reconstructedSignature += typeSignature;
672 if (!msgSignature.startsWith(reconstructedSignature))
673 break;
674 }
675
676 if (reconstructedSignature != msgSignature)
677 continue; // we didn't match them all
678
679 if (hasMessage)
680 ++i;
681
682 // make sure that the output parameters have signatures too
683 if (returnType != 0 && QDBusMetaType::typeToSignature(returnType) == 0)
684 continue;
685
686 bool ok = true;
687 for (int j = i; ok && j < metaTypes.count(); ++j)
688 if (QDBusMetaType::typeToSignature(metaTypes.at(i)) == 0)
689 ok = false;
690 if (!ok)
691 continue;
692
693 // consistency check:
694 if (isAsync && metaTypes.count() > i + 1)
695 continue;
696
697 if (mm.methodType() == QMetaMethod::Slot) {
698 if (isScriptable && (flags & QDBusConnection::ExportScriptableSlots) == 0)
699 continue; // scriptable slots not exported
700 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableSlots) == 0)
701 continue; // non-scriptable slots not exported
702 } else {
703 if (isScriptable && (flags & QDBusConnection::ExportScriptableInvokables) == 0)
704 continue; // scriptable invokables not exported
705 if (!isScriptable && (flags & QDBusConnection::ExportNonScriptableInvokables) == 0)
706 continue; // non-scriptable invokables not exported
707 }
708
709 // if we got here, this slot matched
710 return idx;
711 }
712
713 // no slot matched
714 return -1;
715}
716
717static QDBusCallDeliveryEvent * const DIRECT_DELIVERY = (QDBusCallDeliveryEvent *)1;
718
719QDBusCallDeliveryEvent* QDBusConnectionPrivate::prepareReply(QDBusConnectionPrivate *target,
720 QObject *object, int idx,
721 const QList<int> &metaTypes,
722 const QDBusMessage &msg)
723{
724 Q_ASSERT(object);
725 Q_UNUSED(object);
726
727 int n = metaTypes.count() - 1;
728 if (metaTypes[n] == QDBusMetaTypeId::message)
729 --n;
730
731 if (msg.arguments().count() < n)
732 return 0; // too few arguments
733
734 // check that types match
735 for (int i = 0; i < n; ++i)
736 if (metaTypes.at(i + 1) != msg.arguments().at(i).userType() &&
737 msg.arguments().at(i).userType() != qMetaTypeId<QDBusArgument>())
738 return 0; // no match
739
740 // we can deliver
741 // prepare for the call
742 if (target == object)
743 return DIRECT_DELIVERY;
744 return new QDBusCallDeliveryEvent(QDBusConnection(target), idx, target, msg, metaTypes);
745}
746
747void QDBusConnectionPrivate::activateSignal(const QDBusConnectionPrivate::SignalHook& hook,
748 const QDBusMessage &msg)
749{
750 // This is called by QDBusConnectionPrivate::handleSignal to deliver a signal
751 // that was received from D-Bus
752 //
753 // Signals are delivered to slots if the parameters match
754 // Slots can have less parameters than there are on the message
755 // Slots can optionally have one final parameter that is a QDBusMessage
756 // Slots receive read-only copies of the message (i.e., pass by value or by const-ref)
757 QDBusCallDeliveryEvent *call = prepareReply(this, hook.obj, hook.midx, hook.params, msg);
758 if (call == DIRECT_DELIVERY) {
759 // short-circuit delivery
760 Q_ASSERT(this == hook.obj);
761 deliverCall(this, 0, msg, hook.params, hook.midx);
762 return;
763 }
764 if (call)
765 postEventToThread(ActivateSignalAction, hook.obj, call);
766}
767
768bool QDBusConnectionPrivate::activateCall(QObject* object, int flags, const QDBusMessage &msg)
769{
770 // This is called by QDBusConnectionPrivate::handleObjectCall to place a call
771 // to a slot on the object.
772 //
773 // The call is delivered to the first slot that matches the following conditions:
774 // - has the same name as the message's target member
775 // - ALL of the message's types are found in slot's parameter list
776 // - optionally has one more parameter of type QDBusMessage
777 // If none match, then the slot of the same name as the message target and with
778 // the first type of QDBusMessage is delivered.
779 //
780 // The D-Bus specification requires that all MethodCall messages be replied to, unless the
781 // caller specifically waived this requirement. This means that we inspect if the user slot
782 // generated a reply and, if it didn't, we will. Obviously, if the user slot doesn't take a
783 // QDBusMessage parameter, it cannot generate a reply.
784 //
785 // When a return message is generated, the slot's return type, if any, will be placed
786 // in the message's first position. If there are non-const reference parameters to the
787 // slot, they must appear at the end and will be placed in the subsequent message
788 // positions.
789
790 static const char cachePropertyName[] = "_qdbus_slotCache";
791
792 if (!object)
793 return false;
794
795#ifndef QT_NO_PROPERTIES
796 Q_ASSERT_X(QThread::currentThread() == object->thread(),
797 "QDBusConnection: internal threading error",
798 "function called for an object that is in another thread!!");
799
800 QDBusSlotCache slotCache =
801 qvariant_cast<QDBusSlotCache>(object->property(cachePropertyName));
802 QString cacheKey = msg.member(), signature = msg.signature();
803 if (!signature.isEmpty()) {
804 cacheKey.reserve(cacheKey.length() + 1 + signature.length());
805 cacheKey += QLatin1Char('.');
806 cacheKey += signature;
807 }
808
809 QDBusSlotCache::Hash::ConstIterator cacheIt = slotCache.hash.constFind(cacheKey);
810 while (cacheIt != slotCache.hash.constEnd() && cacheIt->flags != flags &&
811 cacheIt.key() == cacheKey)
812 ++cacheIt;
813 if (cacheIt == slotCache.hash.constEnd() || cacheIt.key() != cacheKey)
814 {
815 // not cached, analyze the meta object
816 const QMetaObject *mo = object->metaObject();
817 QByteArray memberName = msg.member().toUtf8();
818
819 // find a slot that matches according to the rules above
820 QDBusSlotCache::Data slotData;
821 slotData.flags = flags;
822 slotData.slotIdx = ::findSlot(mo, memberName, flags, msg.signature(), slotData.metaTypes);
823 if (slotData.slotIdx == -1) {
824 // ### this is where we want to add the connection as an arg too
825 // try with no parameters, but with a QDBusMessage
826 slotData.slotIdx = ::findSlot(mo, memberName, flags, QString(), slotData.metaTypes);
827 if (slotData.metaTypes.count() != 2 ||
828 slotData.metaTypes.at(1) != QDBusMetaTypeId::message) {
829 // not found
830 // save the negative lookup
831 slotData.slotIdx = -1;
832 slotData.metaTypes.clear();
833 slotCache.hash.insert(cacheKey, slotData);
834 object->setProperty(cachePropertyName, qVariantFromValue(slotCache));
835 return false;
836 }
837 }
838
839 // save to the cache
840 slotCache.hash.insert(cacheKey, slotData);
841 object->setProperty(cachePropertyName, qVariantFromValue(slotCache));
842
843 // found the slot to be called
844 deliverCall(object, flags, msg, slotData.metaTypes, slotData.slotIdx);
845 return true;
846 } else if (cacheIt->slotIdx == -1) {
847 // negative cache
848 return false;
849 } else {
850 // use the cache
851 deliverCall(object, flags, msg, cacheIt->metaTypes, cacheIt->slotIdx);
852 return true;
853 }
854#endif // QT_NO_PROPERTIES
855 return false;
856}
857
858void QDBusConnectionPrivate::deliverCall(QObject *object, int /*flags*/, const QDBusMessage &msg,
859 const QList<int> &metaTypes, int slotIdx)
860{
861 Q_ASSERT_X(!object || QThread::currentThread() == object->thread(),
862 "QDBusConnection: internal threading error",
863 "function called for an object that is in another thread!!");
864
865 QVarLengthArray<void *, 10> params;
866 params.reserve(metaTypes.count());
867
868 QVariantList auxParameters;
869 // let's create the parameter list
870
871 // first one is the return type -- add it below
872 params.append(0);
873
874 // add the input parameters
875 int i;
876 int pCount = qMin(msg.arguments().count(), metaTypes.count() - 1);
877 for (i = 1; i <= pCount; ++i) {
878 int id = metaTypes[i];
879 if (id == QDBusMetaTypeId::message)
880 break;
881
882 const QVariant &arg = msg.arguments().at(i - 1);
883 if (arg.userType() == id)
884 // no conversion needed
885 params.append(const_cast<void *>(arg.constData()));
886 else if (arg.userType() == qMetaTypeId<QDBusArgument>()) {
887 // convert to what the function expects
888 void *null = 0;
889 auxParameters.append(QVariant(id, null));
890
891 const QDBusArgument &in =
892 *reinterpret_cast<const QDBusArgument *>(arg.constData());
893 QVariant &out = auxParameters[auxParameters.count() - 1];
894
895 if (!QDBusMetaType::demarshall(in, out.userType(), out.data()))
896 qFatal("Internal error: demarshalling function for type '%s' (%d) failed!",
897 out.typeName(), out.userType());
898
899 params.append(const_cast<void *>(out.constData()));
900 } else {
901 qFatal("Internal error: got invalid meta type %d (%s) "
902 "when trying to convert to meta type %d (%s)",
903 arg.userType(), QMetaType::typeName(arg.userType()),
904 id, QMetaType::typeName(id));
905 }
906 }
907
908 bool takesMessage = false;
909 if (metaTypes.count() > i && metaTypes[i] == QDBusMetaTypeId::message) {
910 params.append(const_cast<void*>(static_cast<const void*>(&msg)));
911 takesMessage = true;
912 ++i;
913 }
914
915 // output arguments
916 QVariantList outputArgs;
917 void *null = 0;
918 if (metaTypes[0] != QMetaType::Void) {
919 QVariant arg(metaTypes[0], null);
920 outputArgs.append( arg );
921 params[0] = const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData());
922 }
923 for ( ; i < metaTypes.count(); ++i) {
924 QVariant arg(metaTypes[i], null);
925 outputArgs.append( arg );
926 params.append(const_cast<void*>(outputArgs.at( outputArgs.count() - 1 ).constData()));
927 }
928
929 // make call:
930 bool fail;
931 if (!object) {
932 fail = true;
933 } else {
934 // FIXME: save the old sender!
935 QDBusContextPrivate context(QDBusConnection(this), msg);
936 QDBusContextPrivate *old = QDBusContextPrivate::set(object, &context);
937 QDBusConnectionPrivate::setSender(this);
938
939 QPointer<QObject> ptr = object;
940 fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
941 slotIdx, params.data()) >= 0;
942 QDBusConnectionPrivate::setSender(0);
943 // the object might be deleted in the slot
944 if (!ptr.isNull())
945 QDBusContextPrivate::set(object, old);
946 }
947
948 // do we create a reply? Only if the caller is waiting for a reply and one hasn't been sent
949 // yet.
950 if (msg.isReplyRequired() && !msg.isDelayedReply()) {
951 if (!fail) {
952 // normal reply
953 qDBusDebug() << this << "Automatically sending reply:" << outputArgs;
954 send(msg.createReply(outputArgs));
955 } else {
956 // generate internal error
957 qWarning("Internal error: Failed to deliver message");
958 send(msg.createErrorReply(QDBusError::InternalError,
959 QLatin1String("Failed to deliver message")));
960 }
961 }
962
963 return;
964}
965
966extern bool qDBusInitThreads();
967
968QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
969 : QObject(p), ref(1), mode(InvalidMode), connection(0), server(0), busService(0),
970 watchAndTimeoutLock(QMutex::Recursive),
971 rootNode(QString(QLatin1Char('/')))
972{
973 static const bool threads = q_dbus_threads_init_default();
974 static const int debugging = qgetenv("QDBUS_DEBUG").toInt();
975 ::isDebugging = debugging;
976 Q_UNUSED(threads)
977 Q_UNUSED(debugging)
978
979#ifdef QDBUS_THREAD_DEBUG
980 if (debugging > 1)
981 qdbusThreadDebug = qdbusDefaultThreadDebug;
982#endif
983
984 QDBusMetaTypeId::init();
985
986 rootNode.flags = 0;
987
988 // prepopulate watchedServices:
989 // we know that the owner of org.freedesktop.DBus is itself
990 watchedServices.insert(dbusServiceString(), WatchedServiceData(dbusServiceString(), 1));
991
992 // prepopulate matchRefCounts:
993 // we know that org.freedesktop.DBus will never change owners
994 matchRefCounts.insert("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.freedesktop.DBus'", 1);
995}
996
997QDBusConnectionPrivate::~QDBusConnectionPrivate()
998{
999 if (thread() && thread() != QThread::currentThread())
1000 qWarning("QDBusConnection(name=\"%s\")'s last reference in not in its creation thread! "
1001 "Timer and socket errors will follow and the program will probably crash",
1002 qPrintable(name));
1003
1004 closeConnection();
1005 rootNode.children.clear(); // free resources
1006 qDeleteAll(cachedMetaObjects);
1007
1008 if (server)
1009 q_dbus_server_unref(server);
1010 if (connection)
1011 q_dbus_connection_unref(connection);
1012
1013 connection = 0;
1014 server = 0;
1015}
1016
1017void QDBusConnectionPrivate::deleteYourself()
1018{
1019 if (thread() && thread() != QThread::currentThread()) {
1020 // last reference dropped while not in the correct thread
1021 // ask the correct thread to delete
1022
1023 // note: since we're posting an event to another thread, we
1024 // must consider deleteLater() to take effect immediately
1025 deleteLater();
1026 } else {
1027 delete this;
1028 }
1029}
1030
1031void QDBusConnectionPrivate::closeConnection()
1032{
1033 QDBusWriteLocker locker(CloseConnectionAction, this);
1034 ConnectionMode oldMode = mode;
1035 mode = InvalidMode; // prevent reentrancy
1036 baseService.clear();
1037
1038 if (oldMode == ServerMode) {
1039 if (server) {
1040 q_dbus_server_disconnect(server);
1041 }
1042 } else 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
1052void 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
1063bool 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
1074void 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
1086void 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
1120void 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
1127void 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
1147void 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
1166void 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
1182void 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, &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
1221void 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
1237int 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
1251bool 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
1299void 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
1322bool 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
1368void 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
1442void 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
1505QDBusActivateObjectEvent::~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
1517int 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 return -1;
1529}
1530
1531void QDBusConnectionPrivate::handleSignal(const QString &key, const QDBusMessage& msg)
1532{
1533 SignalHookHash::const_iterator it = signalHooks.find(key);
1534 SignalHookHash::const_iterator end = signalHooks.constEnd();
1535 //qDebug("looking for: %s", path.toLocal8Bit().constData());
1536 //qDBusDebug() << signalHooks.keys();
1537 for ( ; it != end && it.key() == key; ++it) {
1538 const SignalHook &hook = it.value();
1539 if (!hook.service.isEmpty()) {
1540 const QString owner =
1541 shouldWatchService(hook.service) ?
1542 watchedServices.value(hook.service).owner :
1543 hook.service;
1544 if (owner != msg.service())
1545 continue;
1546 }
1547 if (!hook.path.isEmpty() && hook.path != msg.path())
1548 continue;
1549 if (!hook.signature.isEmpty() && hook.signature != msg.signature())
1550 continue;
1551 if (hook.signature.isEmpty() && !hook.signature.isNull() && !msg.signature().isEmpty())
1552 continue;
1553 if (!hook.argumentMatch.isEmpty()) {
1554 const QVariantList arguments = msg.arguments();
1555 if (hook.argumentMatch.size() > arguments.size())
1556 continue;
1557
1558 bool matched = true;
1559 for (int i = 0; i < hook.argumentMatch.size(); ++i) {
1560 const QString &param = hook.argumentMatch.at(i);
1561 if (param.isNull())
1562 continue; // don't try to match against this
1563 if (param == arguments.at(i).toString())
1564 continue; // matched
1565 matched = false;
1566 break;
1567 }
1568 if (!matched)
1569 continue;
1570 }
1571
1572 activateSignal(hook, msg);
1573 }
1574}
1575
1576void QDBusConnectionPrivate::handleSignal(const QDBusMessage& msg)
1577{
1578 // We call handlesignal(QString, QDBusMessage) three times:
1579 // one with member:interface
1580 // one with member:
1581 // one with :interface
1582 // This allows us to match signals with wildcards on member or interface
1583 // (but not both)
1584
1585 QString key = msg.member();
1586 key.reserve(key.length() + 1 + msg.interface().length());
1587 key += QLatin1Char(':');
1588 key += msg.interface();
1589
1590 QDBusReadLocker locker(HandleSignalAction, this);
1591 handleSignal(key, msg); // one try
1592
1593 key.truncate(msg.member().length() + 1); // keep the ':'
1594 handleSignal(key, msg); // second try
1595
1596 key = QLatin1Char(':');
1597 key += msg.interface();
1598 handleSignal(key, msg); // third try
1599}
1600
1601static dbus_int32_t server_slot = -1;
1602
1603void QDBusConnectionPrivate::setServer(DBusServer *s, const QDBusErrorInternal &error)
1604{
1605 if (!s) {
1606 handleError(error);
1607 return;
1608 }
1609
1610 server = s;
1611 mode = ServerMode;
1612
1613 dbus_bool_t data_allocated = q_dbus_server_allocate_data_slot(&server_slot);
1614 if (data_allocated && server_slot < 0)
1615 return;
1616
1617 dbus_bool_t watch_functions_set = q_dbus_server_set_watch_functions(server,
1618 qDBusAddWatch,
1619 qDBusRemoveWatch,
1620 qDBusToggleWatch,
1621 this, 0);
1622 //qDebug() << "watch_functions_set" << watch_functions_set;
1623 Q_UNUSED(watch_functions_set);
1624
1625 dbus_bool_t time_functions_set = q_dbus_server_set_timeout_functions(server,
1626 qDBusAddTimeout,
1627 qDBusRemoveTimeout,
1628 qDBusToggleTimeout,
1629 this, 0);
1630 //qDebug() << "time_functions_set" << time_functions_set;
1631 Q_UNUSED(time_functions_set);
1632
1633 q_dbus_server_set_new_connection_function(server, qDBusNewConnection, this, 0);
1634
1635 dbus_bool_t data_set = q_dbus_server_set_data(server, server_slot, this, 0);
1636 //qDebug() << "data_set" << data_set;
1637 Q_UNUSED(data_set);
1638}
1639
1640void QDBusConnectionPrivate::setPeer(DBusConnection *c, const QDBusErrorInternal &error)
1641{
1642 if (!c) {
1643 handleError(error);
1644 return;
1645 }
1646
1647 connection = c;
1648 mode = PeerMode;
1649
1650 q_dbus_connection_set_exit_on_disconnect(connection, false);
1651 q_dbus_connection_set_watch_functions(connection,
1652 qDBusAddWatch,
1653 qDBusRemoveWatch,
1654 qDBusToggleWatch,
1655 this, 0);
1656 q_dbus_connection_set_timeout_functions(connection,
1657 qDBusAddTimeout,
1658 qDBusRemoveTimeout,
1659 qDBusToggleTimeout,
1660 this, 0);
1661 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1662 q_dbus_connection_add_filter(connection,
1663 qDBusSignalFilter,
1664 this, 0);
1665
1666 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1667}
1668
1669void QDBusConnectionPrivate::setConnection(DBusConnection *dbc, const QDBusErrorInternal &error)
1670{
1671 if (!dbc) {
1672 handleError(error);
1673 return;
1674 }
1675
1676 connection = dbc;
1677 mode = ClientMode;
1678
1679 const char *service = q_dbus_bus_get_unique_name(connection);
1680 Q_ASSERT(service);
1681 baseService = QString::fromUtf8(service);
1682
1683 q_dbus_connection_set_exit_on_disconnect(connection, false);
1684 q_dbus_connection_set_watch_functions(connection, qDBusAddWatch, qDBusRemoveWatch,
1685 qDBusToggleWatch, this, 0);
1686 q_dbus_connection_set_timeout_functions(connection, qDBusAddTimeout, qDBusRemoveTimeout,
1687 qDBusToggleTimeout, this, 0);
1688 q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1689 q_dbus_connection_add_filter(connection, qDBusSignalFilter, this, 0);
1690
1691 // Initialize the hooks for the NameAcquired and NameLost signals
1692 // we don't use connectSignal here because we don't need the rules to be sent to the bus
1693 // the bus will always send us these two signals
1694 SignalHook hook;
1695 hook.service = dbusServiceString();
1696 hook.path.clear(); // no matching
1697 hook.obj = this;
1698 hook.params << QMetaType::Void << QVariant::String; // both functions take a QString as parameter and return void
1699
1700 hook.midx = staticMetaObject.indexOfSlot("registerServiceNoLock(QString)");
1701 Q_ASSERT(hook.midx != -1);
1702 signalHooks.insert(QLatin1String("NameAcquired:" DBUS_INTERFACE_DBUS), hook);
1703
1704 hook.midx = staticMetaObject.indexOfSlot("unregisterServiceNoLock(QString)");
1705 Q_ASSERT(hook.midx != -1);
1706 signalHooks.insert(QLatin1String("NameLost:" DBUS_INTERFACE_DBUS), hook);
1707
1708 qDBusDebug() << this << ": connected successfully";
1709
1710 // schedule a dispatch:
1711 QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1712}
1713
1714extern "C"{
1715static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
1716{
1717 QDBusPendingCallPrivate *call = reinterpret_cast<QDBusPendingCallPrivate *>(user_data);
1718 Q_ASSERT(call->pending == pending);
1719 Q_UNUSED(pending);
1720 QDBusConnectionPrivate::processFinishedCall(call);
1721}
1722}
1723
1724void QDBusConnectionPrivate::waitForFinished(QDBusPendingCallPrivate *pcall)
1725{
1726 Q_ASSERT(pcall->pending);
1727 Q_ASSERT(!pcall->autoDelete);
1728 //Q_ASSERT(pcall->mutex.isLocked()); // there's no such function
1729
1730 if (pcall->waitingForFinished) {
1731 // another thread is already waiting
1732 pcall->waitForFinishedCondition.wait(&pcall->mutex);
1733 } else {
1734 pcall->waitingForFinished = true;
1735 pcall->mutex.unlock();
1736
1737 {
1738 QDBusDispatchLocker locker(PendingCallBlockAction, this);
1739 q_dbus_pending_call_block(pcall->pending);
1740 // QDBusConnectionPrivate::processFinishedCall() is called automatically
1741 }
1742 pcall->mutex.lock();
1743 }
1744}
1745
1746void QDBusConnectionPrivate::processFinishedCall(QDBusPendingCallPrivate *call)
1747{
1748 QDBusConnectionPrivate *connection = const_cast<QDBusConnectionPrivate *>(call->connection);
1749
1750 QMutexLocker locker(&call->mutex);
1751
1752 QDBusMessage &msg = call->replyMessage;
1753 if (call->pending) {
1754 // decode the message
1755 DBusMessage *reply = q_dbus_pending_call_steal_reply(call->pending);
1756 msg = QDBusMessagePrivate::fromDBusMessage(reply);
1757 q_dbus_message_unref(reply);
1758 }
1759 qDBusDebug() << connection << "got message reply (async):" << msg;
1760
1761 // Check if the reply has the expected signature
1762 call->checkReceivedSignature();
1763
1764 if (!call->receiver.isNull() && call->methodIdx != -1 && msg.type() == QDBusMessage::ReplyMessage) {
1765 // Deliver the return values of a remote function call.
1766 //
1767 // There is only one connection and it is specified by idx
1768 // The slot must have the same parameter types that the message does
1769 // The slot may have less parameters than the message
1770 // The slot may optionally have one final parameter that is QDBusMessage
1771 // The slot receives read-only copies of the message (i.e., pass by value or by const-ref)
1772
1773 QDBusCallDeliveryEvent *e = prepareReply(connection, call->receiver, call->methodIdx,
1774 call->metaTypes, msg);
1775 if (e)
1776 connection->postEventToThread(MessageResultReceivedAction, call->receiver, e);
1777 else
1778 qDBusDebug() << "Deliver failed!";
1779 }
1780
1781 if (call->pending)
1782 q_dbus_pending_call_unref(call->pending);
1783 call->pending = 0;
1784
1785 locker.unlock();
1786
1787 // Are there any watchers?
1788 if (call->watcherHelper)
1789 call->watcherHelper->emitSignals(msg, call->sentMessage);
1790
1791 if (msg.type() == QDBusMessage::ErrorMessage)
1792 emit connection->callWithCallbackFailed(QDBusError(msg), call->sentMessage);
1793
1794 if (call->autoDelete) {
1795 Q_ASSERT(!call->waitingForFinished); // can't wait on a call with autoDelete!
1796 delete call;
1797 }
1798}
1799
1800int QDBusConnectionPrivate::send(const QDBusMessage& message)
1801{
1802 if (QDBusMessagePrivate::isLocal(message))
1803 return -1; // don't send; the reply will be retrieved by the caller
1804 // through the d_ptr->localReply link
1805
1806 QDBusError error;
1807 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &error);
1808 if (!msg) {
1809 if (message.type() == QDBusMessage::MethodCallMessage)
1810 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1811 qPrintable(message.service()), qPrintable(message.path()),
1812 qPrintable(message.interface()), qPrintable(message.member()),
1813 qPrintable(error.message()));
1814 else if (message.type() == QDBusMessage::SignalMessage)
1815 qWarning("QDBusConnection: error: could not send signal path \"%s\" interface \"%s\" member \"%s\": %s",
1816 qPrintable(message.path()), qPrintable(message.interface()),
1817 qPrintable(message.member()),
1818 qPrintable(error.message()));
1819 else
1820 qWarning("QDBusConnection: error: could not send %s message to service \"%s\": %s",
1821 message.type() == QDBusMessage::ReplyMessage ? "reply" :
1822 message.type() == QDBusMessage::ErrorMessage ? "error" :
1823 "invalid", qPrintable(message.service()),
1824 qPrintable(error.message()));
1825 lastError = error;
1826 return 0;
1827 }
1828
1829 q_dbus_message_set_no_reply(msg, true); // the reply would not be delivered to anything
1830
1831 qDBusDebug() << this << "sending message (no reply):" << message;
1832 checkThread();
1833 bool isOk = q_dbus_connection_send(connection, msg, 0);
1834 int serial = 0;
1835 if (isOk)
1836 serial = q_dbus_message_get_serial(msg);
1837
1838 q_dbus_message_unref(msg);
1839 return serial;
1840}
1841
1842QDBusMessage QDBusConnectionPrivate::sendWithReply(const QDBusMessage &message,
1843 int sendMode, int timeout)
1844{
1845 checkThread();
1846 if ((sendMode == QDBus::BlockWithGui || sendMode == QDBus::Block)
1847 && isServiceRegisteredByThread(message.service()))
1848 // special case for synchronous local calls
1849 return sendWithReplyLocal(message);
1850
1851 if (!QCoreApplication::instance() || sendMode == QDBus::Block) {
1852 QDBusError err;
1853 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &err);
1854 if (!msg) {
1855 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1856 qPrintable(message.service()), qPrintable(message.path()),
1857 qPrintable(message.interface()), qPrintable(message.member()),
1858 qPrintable(err.message()));
1859 lastError = err;
1860 return QDBusMessage::createError(err);
1861 }
1862
1863 qDBusDebug() << this << "sending message (blocking):" << message;
1864 QDBusErrorInternal error;
1865 DBusMessage *reply = q_dbus_connection_send_with_reply_and_block(connection, msg, timeout, error);
1866
1867 q_dbus_message_unref(msg);
1868
1869 if (!!error) {
1870 lastError = err = error;
1871 return QDBusMessage::createError(err);
1872 }
1873
1874 QDBusMessage amsg = QDBusMessagePrivate::fromDBusMessage(reply);
1875 q_dbus_message_unref(reply);
1876 qDBusDebug() << this << "got message reply (blocking):" << amsg;
1877
1878 return amsg;
1879 } else { // use the event loop
1880 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1881 Q_ASSERT(pcall);
1882
1883 if (pcall->replyMessage.type() == QDBusMessage::InvalidMessage) {
1884 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
1885 QEventLoop loop;
1886 loop.connect(pcall->watcherHelper, SIGNAL(reply(QDBusMessage)), SLOT(quit()));
1887 loop.connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), SLOT(quit()));
1888
1889 // enter the event loop and wait for a reply
1890 loop.exec(QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents);
1891 }
1892
1893 QDBusMessage reply = pcall->replyMessage;
1894 lastError = reply; // set or clear error
1895
1896 delete pcall;
1897 return reply;
1898 }
1899}
1900
1901QDBusMessage QDBusConnectionPrivate::sendWithReplyLocal(const QDBusMessage &message)
1902{
1903 qDBusDebug() << this << "sending message via local-loop:" << message;
1904
1905 QDBusMessage localCallMsg = QDBusMessagePrivate::makeLocal(*this, message);
1906 bool handled = handleMessage(localCallMsg);
1907
1908 if (!handled) {
1909 QString interface = message.interface();
1910 if (interface.isEmpty())
1911 interface = QLatin1String("<no-interface>");
1912 return QDBusMessage::createError(QDBusError::InternalError,
1913 QString::fromLatin1("Internal error trying to call %1.%2 at %3 (signature '%4'")
1914 .arg(interface, message.member(),
1915 message.path(), message.signature()));
1916 }
1917
1918 // if the message was handled, there might be a reply
1919 QDBusMessage localReplyMsg = QDBusMessagePrivate::makeLocalReply(*this, localCallMsg);
1920 if (localReplyMsg.type() == QDBusMessage::InvalidMessage) {
1921 qWarning("QDBusConnection: cannot call local method '%s' at object %s (with signature '%s') "
1922 "on blocking mode", qPrintable(message.member()), qPrintable(message.path()),
1923 qPrintable(message.signature()));
1924 return QDBusMessage::createError(
1925 QDBusError(QDBusError::InternalError,
1926 QLatin1String("local-loop message cannot have delayed replies")));
1927 }
1928
1929 // there is a reply
1930 qDBusDebug() << this << "got message via local-loop:" << localReplyMsg;
1931 return localReplyMsg;
1932}
1933
1934QDBusPendingCallPrivate *QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message,
1935 int timeout)
1936{
1937 if (isServiceRegisteredByThread(message.service())) {
1938 // special case for local calls
1939 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1940 pcall->replyMessage = sendWithReplyLocal(message);
1941
1942 return pcall;
1943 }
1944
1945 checkThread();
1946 QDBusPendingCallPrivate *pcall = new QDBusPendingCallPrivate(message, this);
1947 pcall->ref = 0;
1948
1949 QDBusError error;
1950 DBusMessage *msg = QDBusMessagePrivate::toDBusMessage(message, &error);
1951 if (!msg) {
1952 qWarning("QDBusConnection: error: could not send message to service \"%s\" path \"%s\" interface \"%s\" member \"%s\": %s",
1953 qPrintable(message.service()), qPrintable(message.path()),
1954 qPrintable(message.interface()), qPrintable(message.member()),
1955 qPrintable(error.message()));
1956 pcall->replyMessage = QDBusMessage::createError(error);
1957 lastError = error;
1958 return pcall;
1959 }
1960
1961 qDBusDebug() << this << "sending message (async):" << message;
1962 DBusPendingCall *pending = 0;
1963
1964 QDBusDispatchLocker locker(SendWithReplyAsyncAction, this);
1965 if (q_dbus_connection_send_with_reply(connection, msg, &pending, timeout)) {
1966 if (pending) {
1967 q_dbus_message_unref(msg);
1968
1969 pcall->pending = pending;
1970 q_dbus_pending_call_set_notify(pending, qDBusResultReceived, pcall, 0);
1971
1972 return pcall;
1973 } else {
1974 // we're probably disconnected at this point
1975 lastError = error = QDBusError(QDBusError::Disconnected, QLatin1String("Not connected to server"));
1976 }
1977 } else {
1978 lastError = error = QDBusError(QDBusError::NoMemory, QLatin1String("Out of memory"));
1979 }
1980
1981 q_dbus_message_unref(msg);
1982 pcall->replyMessage = QDBusMessage::createError(error);
1983 return pcall;
1984}
1985
1986int QDBusConnectionPrivate::sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
1987 const char *returnMethod, const char *errorMethod,
1988 int timeout)
1989{
1990 QDBusPendingCallPrivate *pcall = sendWithReplyAsync(message, timeout);
1991 Q_ASSERT(pcall);
1992
1993 // has it already finished with success (dispatched locally)?
1994 if (pcall->replyMessage.type() == QDBusMessage::ReplyMessage) {
1995 pcall->setReplyCallback(receiver, returnMethod);
1996 processFinishedCall(pcall);
1997 delete pcall;
1998 return 1;
1999 }
2000
2001 // either it hasn't finished or it has finished with error
2002 if (errorMethod) {
2003 pcall->watcherHelper = new QDBusPendingCallWatcherHelper;
2004 connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
2005 Qt::QueuedConnection);
2006 pcall->watcherHelper->moveToThread(thread());
2007 }
2008
2009 // has it already finished and is an error reply message?
2010 if (pcall->replyMessage.type() == QDBusMessage::ErrorMessage) {
2011 processFinishedCall(pcall);
2012 delete pcall;
2013 return 1;
2014 }
2015
2016 pcall->autoDelete = true;
2017 pcall->ref.ref();
2018 pcall->setReplyCallback(receiver, returnMethod);
2019
2020 return 1;
2021}
2022
2023bool QDBusConnectionPrivate::connectSignal(const QString &service,
2024 const QString &path, const QString &interface, const QString &name,
2025 const QStringList &argumentMatch, const QString &signature,
2026 QObject *receiver, const char *slot)
2027{
2028 // check the slot
2029 QDBusConnectionPrivate::SignalHook hook;
2030 QString key;
2031 QString name2 = name;
2032 if (name2.isNull())
2033 name2.detach();
2034
2035 hook.signature = signature;
2036 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2037 return false; // don't connect
2038
2039 // avoid duplicating:
2040 QDBusConnectionPrivate::SignalHookHash::ConstIterator it = signalHooks.find(key);
2041 QDBusConnectionPrivate::SignalHookHash::ConstIterator end = signalHooks.constEnd();
2042 for ( ; it != end && it.key() == key; ++it) {
2043 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2044 if (entry.service == hook.service &&
2045 entry.path == hook.path &&
2046 entry.signature == hook.signature &&
2047 entry.obj == hook.obj &&
2048 entry.midx == hook.midx &&
2049 entry.argumentMatch == hook.argumentMatch) {
2050 // no need to compare the parameters if it's the same slot
2051 return true; // already there
2052 }
2053 }
2054
2055 connectSignal(key, hook);
2056 return true;
2057}
2058
2059void QDBusConnectionPrivate::connectSignal(const QString &key, const SignalHook &hook)
2060{
2061 signalHooks.insertMulti(key, hook);
2062 connect(hook.obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2063 Qt::ConnectionType(Qt::DirectConnection | Qt::UniqueConnection));
2064
2065 MatchRefCountHash::iterator it = matchRefCounts.find(hook.matchRule);
2066
2067 if (it != matchRefCounts.end()) { // Match already present
2068 it.value() = it.value() + 1;
2069 return;
2070 }
2071
2072 matchRefCounts.insert(hook.matchRule, 1);
2073
2074 if (connection) {
2075 qDBusDebug("Adding rule: %s", hook.matchRule.constData());
2076 QDBusErrorInternal error;
2077 q_dbus_bus_add_match(connection, hook.matchRule, error);
2078 if (!!error) {
2079 QDBusError qerror = error;
2080 qWarning("QDBusConnectionPrivate::connectSignal: received error from D-Bus server "
2081 "while connecting signal to %s::%s: %s (%s)",
2082 hook.obj->metaObject()->className(),
2083 hook.obj->metaObject()->method(hook.midx).signature(),
2084 qPrintable(qerror.name()), qPrintable(qerror.message()));
2085 Q_ASSERT(false);
2086 } else {
2087 // Successfully connected the signal
2088 // Do we need to watch for this name?
2089 if (shouldWatchService(hook.service)) {
2090 WatchedServicesHash::mapped_type &data = watchedServices[hook.service];
2091 if (++data.refcount == 1) {
2092 // we need to watch for this service changing
2093 connectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2094 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2095 this, SLOT(serviceOwnerChangedNoLock(QString,QString,QString)));
2096 data.owner = getNameOwnerNoCache(hook.service);
2097 qDBusDebug() << this << "Watching service" << hook.service << "for owner changes (current owner:"
2098 << data.owner << ")";
2099 }
2100 }
2101 }
2102 }
2103}
2104
2105bool QDBusConnectionPrivate::disconnectSignal(const QString &service,
2106 const QString &path, const QString &interface, const QString &name,
2107 const QStringList &argumentMatch, const QString &signature,
2108 QObject *receiver, const char *slot)
2109{
2110 // check the slot
2111 QDBusConnectionPrivate::SignalHook hook;
2112 QString key;
2113 QString name2 = name;
2114 if (name2.isNull())
2115 name2.detach();
2116
2117 hook.signature = signature;
2118 if (!prepareHook(hook, key, service, path, interface, name, argumentMatch, receiver, slot, 0, false))
2119 return false; // don't disconnect
2120
2121 // avoid duplicating:
2122 QDBusConnectionPrivate::SignalHookHash::Iterator it = signalHooks.find(key);
2123 QDBusConnectionPrivate::SignalHookHash::Iterator end = signalHooks.end();
2124 for ( ; it != end && it.key() == key; ++it) {
2125 const QDBusConnectionPrivate::SignalHook &entry = it.value();
2126 if (entry.service == hook.service &&
2127 entry.path == hook.path &&
2128 entry.signature == hook.signature &&
2129 entry.obj == hook.obj &&
2130 entry.midx == hook.midx &&
2131 entry.argumentMatch == hook.argumentMatch) {
2132 // no need to compare the parameters if it's the same slot
2133 disconnectSignal(it);
2134 return true; // it was there
2135 }
2136 }
2137
2138 // the slot was not found
2139 return false;
2140}
2141
2142QDBusConnectionPrivate::SignalHookHash::Iterator
2143QDBusConnectionPrivate::disconnectSignal(SignalHookHash::Iterator &it)
2144{
2145 const SignalHook &hook = it.value();
2146
2147 bool erase = false;
2148 MatchRefCountHash::iterator i = matchRefCounts.find(hook.matchRule);
2149 if (i == matchRefCounts.end()) {
2150 qWarning("QDBusConnectionPrivate::disconnectSignal: MatchRule not found in matchRefCounts!!");
2151 } else {
2152 if (i.value() == 1) {
2153 erase = true;
2154 matchRefCounts.erase(i);
2155 }
2156 else {
2157 i.value() = i.value() - 1;
2158 }
2159 }
2160
2161 // we don't care about errors here
2162 if (connection && erase) {
2163 qDBusDebug("Removing rule: %s", hook.matchRule.constData());
2164 q_dbus_bus_remove_match(connection, hook.matchRule, NULL);
2165
2166 // Successfully disconnected the signal
2167 // Were we watching for this name?
2168 WatchedServicesHash::Iterator sit = watchedServices.find(hook.service);
2169 if (sit != watchedServices.end()) {
2170 if (--sit.value().refcount == 0) {
2171 watchedServices.erase(sit);
2172 disconnectSignal(dbusServiceString(), QString(), dbusInterfaceString(),
2173 QLatin1String("NameOwnerChanged"), QStringList() << hook.service, QString(),
2174 this, SLOT(_q_serviceOwnerChanged(QString,QString,QString)));
2175 }
2176 }
2177
2178 }
2179
2180 return signalHooks.erase(it);
2181}
2182
2183void QDBusConnectionPrivate::registerObject(const ObjectTreeNode *node)
2184{
2185 connect(node->obj, SIGNAL(destroyed(QObject*)), SLOT(objectDestroyed(QObject*)),
2186 Qt::DirectConnection);
2187
2188 if (node->flags & (QDBusConnection::ExportAdaptors
2189 | QDBusConnection::ExportScriptableSignals
2190 | QDBusConnection::ExportNonScriptableSignals)) {
2191 QDBusAdaptorConnector *connector = qDBusCreateAdaptorConnector(node->obj);
2192
2193 if (node->flags & (QDBusConnection::ExportScriptableSignals
2194 | QDBusConnection::ExportNonScriptableSignals)) {
2195 connector->disconnectAllSignals(node->obj);
2196 connector->connectAllSignals(node->obj);
2197 }
2198
2199 // disconnect and reconnect to avoid duplicates
2200 connector->disconnect(SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2201 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)));
2202 connect(connector, SIGNAL(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2203 this, SLOT(relaySignal(QObject*,const QMetaObject*,int,QVariantList)),
2204 Qt::DirectConnection);
2205 }
2206}
2207
2208void QDBusConnectionPrivate::connectRelay(const QString &service,
2209 const QString &path, const QString &interface,
2210 QDBusAbstractInterface *receiver,
2211 const char *signal)
2212{
2213 // this function is called by QDBusAbstractInterface when one of its signals is connected
2214 // we set up a relay from D-Bus into it
2215 SignalHook hook;
2216 QString key;
2217
2218 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
2219 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2220 return; // don't connect
2221
2222 // add it to our list:
2223 QDBusWriteLocker locker(ConnectRelayAction, this);
2224 SignalHookHash::ConstIterator it = signalHooks.find(key);
2225 SignalHookHash::ConstIterator end = signalHooks.constEnd();
2226 for ( ; it != end && it.key() == key; ++it) {
2227 const SignalHook &entry = it.value();
2228 if (entry.service == hook.service &&
2229 entry.path == hook.path &&
2230 entry.signature == hook.signature &&
2231 entry.obj == hook.obj &&
2232 entry.midx == hook.midx)
2233 return; // already there, no need to re-add
2234 }
2235
2236 connectSignal(key, hook);
2237}
2238
2239void QDBusConnectionPrivate::disconnectRelay(const QString &service,
2240 const QString &path, const QString &interface,
2241 QDBusAbstractInterface *receiver,
2242 const char *signal)
2243{
2244 // this function is called by QDBusAbstractInterface when one of its signals is disconnected
2245 // we remove relay from D-Bus into it
2246 SignalHook hook;
2247 QString key;
2248
2249 if (!prepareHook(hook, key, service, path, interface, QString(), QStringList(), receiver, signal,
2250 QDBusAbstractInterface::staticMetaObject.methodCount(), true))
2251 return; // don't connect
2252
2253 // remove it from our list:
2254 QDBusWriteLocker locker(DisconnectRelayAction, this);
2255 SignalHookHash::Iterator it = signalHooks.find(key);
2256 SignalHookHash::Iterator end = signalHooks.end();
2257 for ( ; it != end && it.key() == key; ++it) {
2258 const SignalHook &entry = it.value();
2259 if (entry.service == hook.service &&
2260 entry.path == hook.path &&
2261 entry.signature == hook.signature &&
2262 entry.obj == hook.obj &&
2263 entry.midx == hook.midx) {
2264 // found it
2265 disconnectSignal(it);
2266 return;
2267 }
2268 }
2269
2270 qWarning("QDBusConnectionPrivate::disconnectRelay called for a signal that was not found");
2271}
2272
2273QString QDBusConnectionPrivate::getNameOwner(const QString& serviceName)
2274{
2275 if (QDBusUtil::isValidUniqueConnectionName(serviceName))
2276 return serviceName;
2277 if (!connection)
2278 return QString();
2279
2280 {
2281 // acquire a read lock for the cache
2282 QReadLocker locker(&lock);
2283 WatchedServicesHash::ConstIterator it = watchedServices.constFind(serviceName);
2284 if (it != watchedServices.constEnd())
2285 return it->owner;
2286 }
2287
2288 // not cached
2289 return getNameOwnerNoCache(serviceName);
2290}
2291
2292QString QDBusConnectionPrivate::getNameOwnerNoCache(const QString &serviceName)
2293{
2294 QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2295 QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2296 QLatin1String("GetNameOwner"));
2297 QDBusMessagePrivate::setParametersValidated(msg, true);
2298 msg << serviceName;
2299 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2300 if (reply.type() == QDBusMessage::ReplyMessage)
2301 return reply.arguments().at(0).toString();
2302 return QString();
2303}
2304
2305QDBusMetaObject *
2306QDBusConnectionPrivate::findMetaObject(const QString &service, const QString &path,
2307 const QString &interface, QDBusError &error)
2308{
2309 // service must be a unique connection name
2310 if (!interface.isEmpty()) {
2311 QDBusReadLocker locker(FindMetaObject1Action, this);
2312 QDBusMetaObject *mo = cachedMetaObjects.value(interface, 0);
2313 if (mo)
2314 return mo;
2315 }
2316
2317 // introspect the target object
2318 QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
2319 QLatin1String(DBUS_INTERFACE_INTROSPECTABLE),
2320 QLatin1String("Introspect"));
2321 QDBusMessagePrivate::setParametersValidated(msg, true);
2322
2323 QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2324
2325 // it doesn't exist yet, we have to create it
2326 QDBusWriteLocker locker(FindMetaObject2Action, this);
2327 QDBusMetaObject *mo = 0;
2328 if (!interface.isEmpty())
2329 mo = cachedMetaObjects.value(interface, 0);
2330 if (mo)
2331 // maybe it got created when we switched from read to write lock
2332 return mo;
2333
2334 QString xml;
2335 if (reply.type() == QDBusMessage::ReplyMessage) {
2336 if (reply.signature() == QLatin1String("s"))
2337 // fetch the XML description
2338 xml = reply.arguments().at(0).toString();
2339 } else {
2340 error = reply;
2341 lastError = error;
2342 if (reply.type() != QDBusMessage::ErrorMessage || error.type() != QDBusError::UnknownMethod)
2343 return 0; // error
2344 }
2345
2346 // release the lock and return
2347 QDBusMetaObject *result = QDBusMetaObject::createMetaObject(interface, xml,
2348 cachedMetaObjects, error);
2349 lastError = error;
2350 return result;
2351}
2352
2353void QDBusConnectionPrivate::registerService(const QString &serviceName)
2354{
2355 QDBusWriteLocker locker(RegisterServiceAction, this);
2356 registerServiceNoLock(serviceName);
2357}
2358
2359void QDBusConnectionPrivate::registerServiceNoLock(const QString &serviceName)
2360{
2361 serviceNames.append(serviceName);
2362}
2363
2364void QDBusConnectionPrivate::unregisterService(const QString &serviceName)
2365{
2366 QDBusWriteLocker locker(UnregisterServiceAction, this);
2367 unregisterServiceNoLock(serviceName);
2368}
2369
2370void QDBusConnectionPrivate::unregisterServiceNoLock(const QString &serviceName)
2371{
2372 serviceNames.removeAll(serviceName);
2373}
2374
2375bool QDBusConnectionPrivate::isServiceRegisteredByThread(const QString &serviceName) const
2376{
2377 if (serviceName == baseService)
2378 return true;
2379 QStringList copy = serviceNames;
2380 return copy.contains(serviceName);
2381}
2382
2383void QDBusConnectionPrivate::postEventToThread(int action, QObject *object, QEvent *ev)
2384{
2385 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::BeforePost, this);
2386 QCoreApplication::postEvent(object, ev);
2387 QDBusLockerBase::reportThreadAction(action, QDBusLockerBase::AfterPost, this);
2388}
2389
2390QT_END_NAMESPACE
2391
2392#endif // QT_NO_DBUS
Note: See TracBrowser for help on using the repository browser.