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