Qt 4.8
qdbusintegrator.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
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 Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/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 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 
42 #include <qcoreapplication.h>
43 #include <qdebug.h>
44 #include <qmetaobject.h>
45 #include <qobject.h>
46 #include <qsocketnotifier.h>
47 #include <qstringlist.h>
48 #include <qtimer.h>
49 #include <qthread.h>
50 
51 #include "qdbusargument.h"
52 #include "qdbusconnection_p.h"
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 
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 
78 static inline QString dbusServiceString()
79 { return *orgFreedesktopDBusString(); }
81 {
82  // it's the same string, but just be sure
83  Q_ASSERT(*orgFreedesktopDBusString() == QLatin1String(DBUS_INTERFACE_DBUS));
84  return *orgFreedesktopDBusString();
85 }
86 
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
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 
112 Q_AUTOTEST_EXPORT void qdbusDefaultThreadDebug(int action, int condition, QDBusConnectionPrivate *conn)
113 {
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&);
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 
151 
152  if (!q_dbus_timeout_get_enabled(timeout))
153  return true;
154 
157  // correct thread
158  return qDBusRealAddTimeout(d, timeout, q_dbus_timeout_get_interval(timeout));
159  } else {
160  // wrong thread: sync back
163  d->timeoutsPendingAdd.append(qMakePair(timeout, q_dbus_timeout_get_interval(timeout)));
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 
189 
191 
192  // is it pending addition?
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();
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
213  ev->timerId = it.key();
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 
242 
243  int flags = q_dbus_watch_get_flags(watch);
244  int fd = q_dbus_watch_get_fd(watch);
245 
247  return qDBusRealAddWatch(d, watch, flags, fd);
248  } else {
251  ev->watch = watch;
252  ev->fd = fd;
253  ev->extra = flags;
255  return true;
256  }
257 }
258 
259 static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd)
260 {
262 
264  if (flags & DBUS_WATCH_READABLE) {
265  //qDebug("addReadWatch %d", fd);
266  watcher.watch = watch;
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;
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 
295  int fd = q_dbus_watch_get_fd(watch);
296 
299  while (i != d->watchers.end() && i.key() == fd) {
300  if (i.value().watch == watch) {
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 
326  int fd = q_dbus_watch_get_fd(watch);
327 
329  qDBusRealToggleWatch(d, watch, fd);
330  } else {
333  ev->watch = watch;
334  ev->fd = fd;
336  }
337 }
338 
339 static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd)
340 {
342 
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);
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)
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());
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
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 
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 
437  const QString &fullpath, int &usedLength,
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) {
454  break;
456  break;
457  int end = fullpath.indexOf(QLatin1Char('/'), start);
458  end = (end == -1 ? length : end);
459  QStringRef pathComponent(&fullpath, start, end - start);
460 
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 
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;
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 
528 static bool shouldWatchService(const QString &service)
529 {
530  return !service.isEmpty() && !service.startsWith(QLatin1Char(':'));
531 }
532 
535 {
536  qDBusSpyHookList()->append(hook);
537 }
538 
539 extern "C" {
540 static DBusHandlerResult
541 qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
542 {
543  Q_ASSERT(data);
544  Q_UNUSED(connection);
547  return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
548 
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 
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()) {
571  handleSignal(amsg);
572  // if there are any other filters in this DBusConnection,
573  // let them see the signal too
574  return false;
576  handleObjectCall(amsg);
577  return true;
581  return false; // we don't handle those here
582  }
583 
584  return false;
585 }
586 
588 {
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 
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 {
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
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 
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:
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 
730 
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 
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)
778 }
779 
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
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();
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 
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 
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);
948 
949  QPointer<QObject> ptr = object;
950  fail = object->qt_metacall(QMetaObject::InvokeMetaMethod,
951  slotIdx, params.data()) >= 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");
969  QLatin1String("Failed to deliver message")));
970  }
971  }
972 
973  return;
974 }
975 
976 extern bool qDBusInitThreads();
977 
979  : QObject(p), ref(1), capabilities(0), mode(InvalidMode), connection(0), server(0), busService(0),
980  watchAndTimeoutLock(QMutex::Recursive),
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 
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 
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
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 
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 
1042 {
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 
1062 {
1063  if (!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 
1073 {
1074  if (!error)
1075  return false; // no error
1076 
1077  //lock.lockForWrite();
1078  lastError = error;
1079  //lock.unlock();
1080  return true;
1081 }
1082 
1084 {
1085  {
1087  DBusTimeout *timeout = timeouts.value(e->timerId(), 0);
1088  if (timeout)
1089  q_dbus_timeout_handle(timeout);
1090  }
1091 
1092  doDispatch();
1093 }
1094 
1096 {
1097  Q_ASSERT(e->type() == QEvent::User);
1098 
1100  QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1102  switch (ev->subtype)
1103  {
1106  while (!timeoutsPendingAdd.isEmpty()) {
1108  qDBusRealAddTimeout(this, entry.first, entry.second);
1109  }
1110  break;
1111  }
1112 
1114  killTimer(ev->timerId);
1115  break;
1116 
1118  qDBusRealAddWatch(this, ev->watch, ev->extra, ev->fd);
1119  break;
1120 
1122  qDBusRealToggleWatch(this, ev->watch, ev->fd);
1123  break;
1124  }
1125  QDBusLockerBase::reportThreadAction(int(AddTimeoutAction) + int(ev->subtype),
1127 }
1128 
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 
1137 {
1138  QVarLengthArray<DBusWatch *, 2> pendingWatches;
1139 
1140  {
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 
1157 {
1158  QVarLengthArray<DBusWatch *, 2> pendingWatches;
1159 
1160  {
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 
1176 {
1178  huntAndDestroy(obj, rootNode);
1179 
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 
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())
1205  isAdaptor = true;
1206  break;
1207  }
1208 
1209  QDBusReadLocker locker(RelaySignalAction, this);
1210  QDBusMessage message = QDBusMessage::createSignal(QLatin1String("/"), interface,
1211  QLatin1String(memberName));
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 
1231  const QString &oldOwner, const QString &newOwner)
1232 {
1233  Q_UNUSED(oldOwner);
1234 // QDBusWriteLocker locker(UpdateSignalHookOwnerAction, this);
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 
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 
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)
1302  }
1303 
1304  hook.matchRule = buildMatchRule(service, path, interface, mname, argMatch, hook.signature);
1305  return true; // connect to this signal
1306 }
1307 
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) {
1323  QString::fromLatin1("No such interface '%1' at object path '%2'")
1324  .arg(msg.interface(), msg.path())));
1325  } else if (code == QDBusError::UnknownObject) {
1327  QString::fromLatin1("No such object path '%1'").arg(msg.path())));
1328  }
1329 }
1330 
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()) {
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()) {
1370  return true;
1371  }
1372  }
1373 
1374  return false;
1375 }
1376 
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 
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) {
1401  return;
1402  }
1403  }
1404 
1405  QDBusAdaptorConnector *connector;
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
1414  connector->adaptors.constBegin();
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:
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))
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:
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))
1449  return;
1450  }
1451  }
1452 
1453  // nothing matched, send an error code
1454  if (msg.interface().isEmpty())
1456  else
1458 }
1459 
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  {
1477  if (!findObject(&rootNode, msg.path(), usedLength, result)) {
1478  // qDebug("Call failed: no object found at %s", qPrintable(msg.path()));
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) {
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
1503  new QDBusActivateObjectEvent(QDBusConnection(this), this, result,
1504  usedLength, msg));
1505  return;
1506  } else if (objThread != QThread::currentThread()) {
1507  // synchronize with other thread
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)
1519  else
1520  activateObject(result, msg, usedLength);
1521 }
1522 
1524 {
1525  if (!handled) {
1526  // we're being destroyed without delivering
1527  // it means the object was deleted between posting and delivering
1529  that->sendError(message, QDBusError::UnknownObject);
1530  }
1531 
1532  // semaphore releasing happens in ~QMetaCallEvent
1533 }
1534 
1536 {
1538 
1541  that->activateObject(node, message, pathStartPos);
1544 
1545  handled = true;
1546 }
1547 
1549 {
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 
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 
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,
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,
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 
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,
1672  this, 0);
1673  q_dbus_connection_set_timeout_functions(connection,
1677  this, 0);
1678  q_dbus_connection_set_dispatch_status_function(connection, qDBusUpdateDispatchStatus, this, 0);
1679  q_dbus_connection_add_filter(connection,
1681  this, 0);
1682 
1683  QMetaObject::invokeMethod(this, "doDispatch", Qt::QueuedConnection);
1684 }
1685 
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))
1706 
1707  return result;
1708 }
1709 
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"{
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);
1763 }
1764 }
1765 
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  {
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 
1791  }
1792 }
1793 
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)
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 
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 
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;
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 
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 
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
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 
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>");
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()));
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 
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) {
1998  connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
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) {
2022  connect(pcall->watcherHelper, SIGNAL(error(QDBusError,QDBusMessage)), receiver, errorMethod,
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 
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 
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
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:
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 
2112 {
2113  signalHooks.insertMulti(key, hook);
2116 
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) {
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)) {
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(),
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 
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
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:
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 
2188 {
2189  const SignalHook &hook = it.value();
2190 
2191  bool erase = false;
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) {
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?
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 
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 
2243 {
2246 
2251 
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)),
2264  }
2265 
2266  static int counter = 0;
2267  if ((++counter % 20) == 0)
2269 }
2270 
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);
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 
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:
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 
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);
2347  if (it != watchedServices.constEnd())
2348  return it->owner;
2349  }
2350 
2351  // not cached
2352  return getNameOwnerNoCache(serviceName);
2353 }
2354 
2356 {
2357  QDBusMessage msg = QDBusMessage::createMethodCall(dbusServiceString(),
2358  QLatin1String(DBUS_PATH_DBUS), dbusInterfaceString(),
2359  QLatin1String("GetNameOwner"));
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 
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"));
2385 
2386  QDBusMessage reply = sendWithReply(msg, QDBus::Block);
2387 
2388  // it doesn't exist yet, we have to create it
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 
2417 {
2419  registerServiceNoLock(serviceName);
2420 }
2421 
2423 {
2424  serviceNames.append(serviceName);
2425 }
2426 
2428 {
2430  unregisterServiceNoLock(serviceName);
2431 }
2432 
2434 {
2435  serviceNames.removeAll(serviceName);
2436 }
2437 
2439 {
2440  if (!serviceName.isEmpty() && serviceName == baseService)
2441  return true;
2442  QStringList copy = serviceNames;
2443  return copy.contains(serviceName);
2444 }
2445 
2447 {
2449  QCoreApplication::postEvent(object, ev);
2451 }
2452 
2454 
2455 #endif // QT_NO_DBUS
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qstring.cpp:6448
The QVariant class acts like a union for the most common Qt data types.
Definition: qvariant.h:92
Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook)
QVarLengthArray< QDBusSpyHook, 4 > QDBusSpyHookList
int startTimer(int interval)
Starts a timer and returns a timer identifier, or returns zero if it could not start a timer...
Definition: qobject.cpp:1623
The QDebug class provides an output stream for debugging information.
Definition: qdebug.h:62
QAtomicInt ref
Definition: qshareddata.h:59
double d
Definition: qnumeric_p.h:62
The QMetaObject class contains meta-information about Qt objects.
Definition: qobjectdefs.h:304
static QDBusMessage createError(const QString &name, const QString &msg)
Constructs a new DBus message representing an error, with the given name and msg. ...
void handleObjectCall(const QDBusMessage &message)
Q_CORE_EXPORT QByteArray qgetenv(const char *varName)
void callWithCallbackFailed(const QDBusError &error, const QDBusMessage &message)
void setServer(DBusServer *server, const QDBusErrorInternal &error)
static dbus_int32_t server_slot
void truncate(int pos)
Truncates the byte array at index position pos.
void activateObject(ObjectTreeNode &node, const QDBusMessage &msg, int pathStartPos)
unsigned char c[8]
Definition: qnumeric_p.h:62
Q_DECL_CONSTEXPR const T & qMin(const T &a, const T &b)
Definition: qglobal.h:1215
static bool isLocal(const QDBusMessage &msg)
#define QT_END_NAMESPACE
This macro expands to.
Definition: qglobal.h:90
void lock()
Locks the mutex.
Definition: qmutex.cpp:151
The QSemaphore class provides a general counting semaphore.
Definition: qsemaphore.h:57
QDBusAdaptorConnector * qDBusFindAdaptorConnector(QObject *obj)
The QMutex class provides access serialization between threads.
Definition: qmutex.h:60
static bool findObject(const QDBusConnectionPrivate::ObjectTreeNode *root, const QString &fullpath, int &usedLength, QDBusConnectionPrivate::ObjectTreeNode &result)
static QByteArray normalizedSignature(const char *method)
Normalizes the signature of the given method.
static QByteArray buildMatchRule(const QString &service, const QString &objectPath, const QString &interface, const QString &member, const QStringList &argMatch, const QString &)
QHash< Key, T >::const_iterator constFind(const Key &key, const T &value) const
Returns an iterator pointing to the item with the key and the value in the hash.
Definition: qhash.h:992
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
static QDBusMessage createSignal(const QString &path, const QString &interface, const QString &name)
Constructs a new DBus message with the given path, interface and name, representing a signal emission...
static void qDBusNewConnection(DBusServer *server, DBusConnection *connection, void *data)
#define it(className, varName)
bool isNull() const
Returns true if the referenced object has been destroyed or if there is no referenced object; otherwi...
Definition: qpointer.h:70
static void huntAndEmit(DBusConnection *connection, DBusMessage *msg, QObject *needle, const QDBusConnectionPrivate::ObjectTreeNode &haystack, bool isScriptable, bool isAdaptor, const QString &path=QString())
The QDBusArgument class is used to marshall and demarshall D-Bus arguments.
Definition: qdbusargument.h:69
QDBusAdaptorConnector * qDBusCreateAdaptorConnector(QObject *obj)
static void postEvent(QObject *receiver, QEvent *event)
Adds the event event, with the object receiver as the receiver of the event, to an event queue and re...
QDebug & nospace()
Clears the stream&#39;s internal flag that records whether the last character was a space and returns a r...
Definition: qdebug.h:92
static bool isDebugging
QByteArray toUtf8() const Q_REQUIRED_RESULT
Returns a UTF-8 representation of the string as a QByteArray.
Definition: qstring.cpp:4074
void serviceOwnerChangedNoLock(const QString &name, const QString &oldOwner, const QString &newOwner)
#define error(msg)
QString objectName
the name of this object
Definition: qobject.h:114
bool handleError(const QDBusErrorInternal &error)
static QDBusConnectionPrivate * d(const QDBusConnection &q)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
void chop(int n)
Removes n characters from the end of the string.
Definition: qstring.cpp:4623
int length() const
Returns the number of characters in this string.
Definition: qstring.h:696
#define SLOT(a)
Definition: qobjectdefs.h:226
QString service() const
Returns the name of the service or the bus address of the remote method call.
#define DBUS_TYPE_UNIX_FD
const_iterator ConstIterator
Qt-style synonym for QHash::const_iterator.
Definition: qhash.h:474
T1 first
Definition: qpair.h:65
bool setReplyCallback(QObject *target, const char *member)
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the vector...
Definition: qvector.h:252
void unlock()
Unlocks this mutex locker.
Definition: qmutex.h:117
T2 second
Definition: qpair.h:66
The QDBusError class represents an error received from the D-Bus bus or from remote applications foun...
Definition: qdbuserror.h:60
void disconnectAllSignals(QObject *object)
iterator begin()
Returns an STL-style iterator pointing to the first item in the list.
Definition: qlist.h:267
QString toString() const
Returns the variant as a QString if the variant has type() String , Bool , ByteArray ...
Definition: qvariant.cpp:2270
const_iterator constBegin() const
Returns a const STL-style iterator pointing to the first item in the list.
Definition: qlist.h:269
void registerServiceNoLock(const QString &serviceName)
static const QMetaObject staticMetaObject
This variable stores the meta-object for the class.
Definition: qobject.h:128
WatchedServiceData mapped_type
Typedef for T.
Definition: qhash.h:484
static dbus_bool_t qDBusAddWatch(DBusWatch *watch, void *data)
bool startsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string starts with s; otherwise returns false.
Definition: qstring.cpp:3734
void * qdbus_resolve_conditionally(const char *name)
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
static QDBusConnection q(QDBusConnectionPrivate *connection)
virtual bool handleMessage(const QDBusMessage &message, const QDBusConnection &connection)=0
This function needs to handle all messages to the path of the virtual object, when the SubPath option...
int count(const T &t) const
Returns the number of occurrences of value in the list.
Definition: qlist.h:891
void deliverCall(QObject *object, int flags, const QDBusMessage &msg, const QList< int > &metaTypes, int slotIdx)
void handleSignal(const QString &key, const QDBusMessage &msg)
T & value() const
Returns a modifiable reference to the current item&#39;s value.
Definition: qhash.h:348
MatchRefCountHash matchRefCounts
The QString class provides a Unicode character string.
Definition: qstring.h:83
const char * typeName() const
Returns the return type of this method, or an empty string if the return type is void.
static void processFinishedCall(QDBusPendingCallPrivate *call)
static QWidget * owner
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
static int findSlot(QObject *obj, const QByteArray &normalizedName, QList< int > &params)
void relaySignal(QObject *obj, const QMetaObject *, int signalId, const QVariantList &args)
bool startsWith(const QByteArray &a) const
Returns true if this byte array starts with byte array ba; otherwise returns false.
static void setSender(const QDBusConnectionPrivate *s)
DBusConnection * connection
MetaObjectHash cachedMetaObjects
void append(const T &t)
QHash< Key, T >::iterator find(const Key &key, const T &value)
Returns an iterator pointing to the item with the key and value.
Definition: qhash.h:972
static QDBusCallDeliveryEvent *const DIRECT_DELIVERY
iterator Iterator
Qt-style synonym for QVector::iterator.
Definition: qvector.h:278
const T value(const Key &key) const
Returns the value associated with the key.
Definition: qhash.h:606
bool qDBusCheckAsyncTag(const char *tag)
Definition: qdbusmisc.cpp:57
void connectAllSignals(QObject *object)
int qDBusParametersForMethod(const QMetaMethod &mm, QList< int > &metaTypes)
Definition: qdbusmisc.cpp:137
ErrorType
In order to facilitate verification of the most common D-Bus errors generated by the D-Bus implementa...
Definition: qdbuserror.h:63
ErrorType type() const
Returns this error&#39;s ErrorType.
Definition: qdbuserror.cpp:323
bool isEmpty() const
Returns true if the list contains no items; otherwise returns false.
Definition: qlist.h:152
iterator insert(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition: qhash.h:753
The QSocketNotifier class provides support for monitoring activity on a file descriptor.
iterator end()
Returns an STL-style iterator pointing to the imaginary item after the last item in the vector...
Definition: qvector.h:250
static QDBusMessage fromDBusMessage(DBusMessage *dmsg, QDBusConnection::ConnectionCapabilities capabilities)
Constructs a QDBusMessage by parsing the given DBusMessage object.
QDBusMessage createErrorReply(const QString name, const QString &msg) const
Constructs a new DBus message representing an error reply message, with the given name and msg...
ConnectionType
Definition: qnamespace.h:1469
static bool 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)
Q_CORE_EXPORT void qDebug(const char *,...)
static QDBusConnectionManager * instance()
static void qDBusResultReceived(DBusPendingCall *pending, void *user_data)
QString signature() const
Returns the signature of the signal that was received or for the output arguments of a method call...
void reserve(int size)
Attempts to allocate memory for at least size characters.
Definition: qstring.h:881
#define SIGNAL(a)
Definition: qobjectdefs.h:227
const_iterator constBegin() const
Returns a const STL-style iterator pointing to the first item in the vector.
Definition: qvector.h:249
static QDBusMetaObject * createMetaObject(const QString &interface, const QString &xml, QHash< QString, QDBusMetaObject *> &map, QDBusError &error)
static void setParametersValidated(QDBusMessage &msg, bool enable)
static const char * typeToSignature(int type)
Returns the D-Bus signature equivalent to the supplied meta type id type.
bool activateCall(QObject *object, int flags, const QDBusMessage &msg)
static QThread * currentThread()
Returns a pointer to a QThread which manages the currently executing thread.
Definition: qthread.cpp:419
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
void * data()
Definition: qvariant.cpp:3077
The QDBusAbstractInterface class is the base class for all D-Bus interfaces in the QtDBus binding...
#define QT_BEGIN_NAMESPACE
This macro expands to.
Definition: qglobal.h:89
QList< QVariant > arguments() const
Returns the list of arguments that are going to be sent or were received from D-Bus.
static QDBusMessage makeLocal(const QDBusConnectionPrivate &conn, const QDBusMessage &asSent)
static bool demarshall(const QDBusArgument &, int id, void *data)
Executes the demarshalling of type id (whose data will be placed in data) from the D-Bus marshalling ...
QString path() const
Returns the path of the object that this message is being sent to (in the case of a method call) or b...
void destroyed(QObject *=0)
This signal is emitted immediately before the object obj is destroyed, and can not be blocked...
QDBusMetaObject * findMetaObject(const QString &service, const QString &path, const QString &interface, QDBusError &error)
The QEventLoop class provides a means of entering and leaving an event loop.
Definition: qeventloop.h:55
void truncate(int pos)
Truncates the string at the given position index.
Definition: qstring.cpp:4603
static void qDBusRemoveTimeout(DBusTimeout *timeout, void *data)
void clear()
Removes all the elements from the vector and releases the memory used by the vector.
Definition: qvector.h:347
T takeFirst()
Removes the first item in the list and returns it.
Definition: qlist.h:489
static bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
Creates a connection of the given type from the signal in the sender object to the method in the rece...
Definition: qobject.cpp:2580
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
QDBusMessage sendWithReply(const QDBusMessage &message, int mode, int timeout=-1)
static int message
void disconnectRelay(const QString &service, const QString &path, const QString &interface, QDBusAbstractInterface *receiver, const char *signal)
iterator end()
Returns an STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:270
const QDBusMessage sentMessage
void activateSignal(const SignalHook &hook, const QDBusMessage &msg)
QPointer< QObject > receiver
#define Q_GLOBAL_STATIC(TYPE, NAME)
Declares a global static variable with the given type and name.
Definition: qglobal.h:1968
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
void unregisterServiceNoLock(const QString &serviceName)
#define emit
Definition: qobjectdefs.h:76
bool deref()
Atomically decrements the value of this QAtomicInt.
bool isReplyRequired() const
Returns the flag that indicates if this message should see a reply or not.
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
bool connectSignal(const QString &service, const QString &path, const QString &interface, const QString &name, const QStringList &argumentMatch, const QString &signature, QObject *receiver, const char *slot)
static QString fromUtf8(const char *, int size=-1)
Returns a QString initialized with the first size bytes of the UTF-8 string str.
Definition: qstring.cpp:4302
SignalHookHash::Iterator disconnectSignal(SignalHookHash::Iterator &it)
Q_CORE_EXPORT void qWarning(const char *,...)
static DBusMessage * toDBusMessage(const QDBusMessage &message, QDBusConnection::ConnectionCapabilities capabilities, QDBusError *error)
Constructs a DBusMessage object from message.
int timerId() const
Returns the unique timer identifier, which is the same identifier as returned from QObject::startTime...
Definition: qcoreevent.h:346
void connectRelay(const QString &service, const QString &path, const QString &interface, QDBusAbstractInterface *receiver, const char *signal)
static const char * data(const QByteArray &arr)
int indexOf(QChar c, int from=0, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Definition: qstring.cpp:2838
The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal...
Definition: qstring.h:654
const_iterator constFind(const Key &key) const
Returns an iterator pointing to the item with the key in the hash.
Definition: qhash.h:859
static void init()
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
void moveToThread(QThread *thread)
Changes the thread affinity for this object and its children.
Definition: qobject.cpp:1458
void setConnection(const QString &name, QDBusConnectionPrivate *c)
int indexOfSlot(const char *slot) const
Finds slot and returns its index; otherwise returns -1.
const T * ptr(const T &t)
QByteArray toLatin1() const Q_REQUIRED_RESULT
Returns a Latin-1 representation of the string as a QByteArray.
Definition: qstring.cpp:3993
void emitSignals(const QDBusMessage &replyMessage, const QDBusMessage &sentMessage)
void clear()
Removes all items from the list.
Definition: qlist.h:764
void waitForFinished(QDBusPendingCallPrivate *pcall)
QString member() const
Returns the name of the signal that was emitted or the name of the method that was called...
const Key & key() const
Returns the current item&#39;s key as a const reference.
Definition: qhash.h:347
The QReadLocker class is a convenience class that simplifies locking and unlocking read-write locks f...
static void qDBusToggleTimeout(DBusTimeout *timeout, void *data)
QDBusConnection::ConnectionCapabilities capabilities
static QVariant fromValue(const T &value)
Returns a QVariant containing a copy of value.
Definition: qvariant.h:336
void detach()
Definition: qstring.h:714
const QMetaObject * superClass() const
Returns the meta-object of the superclass, or 0 if there is no such object.
Definition: qobjectdefs.h:494
QDBusPendingCallPrivate * sendWithReplyAsync(const QDBusMessage &message, QObject *receiver, const char *returnMethod, const char *errorMethod, int timeout=-1)
bool isDelayedReply() const
Returns the delayed reply flag, as set by setDelayedReply().
const char * typeName() const
Returns the name of the type stored in the variant.
Definition: qvariant.cpp:1984
friend class QDBusCallDeliveryEvent
int indexOf(char c, int from=0) const
Returns the index position of the first occurrence of the character ch in the byte array...
void unregisterService(const QString &serviceName)
void unlock()
Unlocks the mutex.
Definition: qmutex.cpp:296
QDBusMessage qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode &node, const QDBusMessage &msg)
static QDBusCallDeliveryEvent * prepareReply(QDBusConnectionPrivate *target, QObject *object, int idx, const QList< int > &metaTypes, const QDBusMessage &msg)
The QStringRef class provides a thin wrapper around QString substrings.
Definition: qstring.h:1099
PendingTimeoutList timeoutsPendingAdd
bool isValidUniqueConnectionName(const QString &connName)
Returns true if connName is a valid unique connection name.
Definition: qdbusutil.cpp:393
bool wait(QMutex *mutex, unsigned long time=ULONG_MAX)
Q_GLOBAL_STATIC_WITH_ARGS(const QString, orgFreedesktopDBusString,(QLatin1String(DBUS_SERVICE_DBUS))) static inline QString dbusServiceString()
QDBusMessage createReply(const QList< QVariant > &arguments=QList< QVariant >()) const
Constructs a new DBus message representing a reply, with the given arguments.
int length() const
Same as size().
Definition: qbytearray.h:356
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
MethodType methodType() const
Returns the type of this method (signal, slot, or method).
QHash< Key, T >::iterator insert(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition: qhash.h:934
bool isNull() const
Returns true if this string is null; otherwise returns false.
Definition: qstring.h:505
QString interface() const
Returns the interface of the method being called (in the case of a method call) or of the signal bein...
static bool disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *member)
Disconnects signal in object sender from method in object receiver.
Definition: qobject.cpp:2895
void objectDestroyed(QObject *o)
int qDBusNameToTypeId(const char *name)
Definition: qdbusmisc.cpp:72
QDBusMessage qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode &node, const QDBusMessage &msg)
Q_OUTOFLINE_TEMPLATE RandomAccessIterator qLowerBound(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
Definition: qalgorithms.h:227
static QString dbusInterfaceString()
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the hash...
Definition: qhash.h:469
QDBusMessage qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode &node, const QDBusMessage &msg)
static QAuServer & server()
Definition: qsound.cpp:79
Q_CORE_EXPORT void qFatal(const char *,...)
static void qDBusUpdateDispatchStatus(DBusConnection *connection, DBusDispatchStatus new_status, void *data)
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
iterator erase(iterator pos)
Removes the item associated with the iterator pos from the list, and returns an iterator to the next ...
Definition: qlist.h:464
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
QString arg(qlonglong a, int fieldwidth=0, int base=10, const QChar &fillChar=QLatin1Char(' ')) const Q_REQUIRED_RESULT
Definition: qstring.cpp:7186
int userType() const
Returns the storage type of the value stored in the variant.
Definition: qvariant.cpp:1913
bool handleMessage(const QDBusMessage &msg)
#define qDBusDebug
#define SEM_ACQUIRE(action, sem)
int compare(const QString &s) const
Definition: qstring.cpp:5037
static bool qDBusRealAddTimeout(QDBusConnectionPrivate *d, DBusTimeout *timeout, int ms)
void timerEvent(QTimerEvent *e)
This event handler can be reimplemented in a subclass to receive timer events for the object...
bool isServiceRegisteredByThread(const QString &serviceName) const
void registerObject(const ObjectTreeNode *node)
QString getNameOwnerNoCache(const QString &service)
iterator end()
Returns an STL-style iterator pointing to the imaginary item after the last item in the hash...
Definition: qhash.h:467
The QTimerEvent class contains parameters that describe a timer event.
Definition: qcoreevent.h:341
iterator begin()
Returns an STL-style iterator pointing to the first item in the vector.
Definition: qvector.h:247
static bool shouldWatchService(const QString &service)
static QCoreApplication * instance()
Returns a pointer to the application&#39;s QCoreApplication (or QApplication) instance.
void clear()
Clears the contents of the string and makes it empty.
Definition: qstring.h:723
static const char * typeName(int type)
Returns the type name associated with the given type, or 0 if no matching type was found...
Definition: qmetatype.cpp:406
The QDBusConnection class represents a connection to the D-Bus bus daemon.
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
const char * tag() const
Returns the tag associated with this method.
QDBusPendingCallWatcherHelper * watcherHelper
static QDBusMessage createMethodCall(const QString &destination, const QString &path, const QString &interface, const QString &method)
Constructs a new DBus message representing a method call.
int indexOfMethod(const char *method) const
Finds method and returns its index; otherwise returns -1.
bool qDBusInterfaceInObject(QObject *obj, const QString &interface_name)
Definition: qdbusmisc.cpp:116
int toInt(bool *ok=0, int base=10) const
Returns the byte array converted to an int using base base, which is 10 by default and must be betwee...
QObject * parent() const
Returns a pointer to the parent object.
Definition: qobject.h:273
Q_OUTOFLINE_TEMPLATE QPair< T1, T2 > qMakePair(const T1 &x, const T2 &y)
Definition: qpair.h:102
WatchedServicesHash watchedServices
const void * constData() const
Definition: qvariant.cpp:3065
const_iterator ConstIterator
Qt-style synonym for QList::const_iterator.
Definition: qlist.h:279
int key
void setPeer(DBusConnection *connection, const QDBusErrorInternal &error)
QDBusMessage sendWithReplyLocal(const QDBusMessage &message)
QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node, const QString &path)
The QHash::iterator class provides an STL-style non-const iterator for QHash and QMultiHash.
Definition: qhash.h:330
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
static bool qDBusRealAddWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int flags, int fd)
void setEnabled(bool)
If enable is true, the notifier is enabled; otherwise the notifier is disabled.
void sendError(const QDBusMessage &msg, QDBusError::ErrorType code)
QString objectName() const
static void qDBusRealToggleWatch(QDBusConnectionPrivate *d, DBusWatch *watch, int fd)
#define Q_DBUS_EXPORT
Definition: qglobal.h:1463
if(void) toggleToolbarShown
#define Q_AUTOTEST_EXPORT
Definition: qglobal.h:1510
iterator begin()
Returns an STL-style iterator pointing to the first item in the hash.
Definition: qhash.h:464
const QObjectList & children() const
Returns a list of child objects.
Definition: qobject.h:197
QDBusConnectionPrivate *const connection
enum QDBusConnectionCallbackEvent::Subtype subtype
DBusPendingCall * pending
T qvariant_cast(const QVariant &)
Definition: qvariant.h:571
static QDBusContextPrivate * set(QObject *obj, QDBusContextPrivate *newContext)
int attributes() const
volatile bool waitingForFinished
static void qDBusToggleWatch(DBusWatch *watch, void *data)
The QDBusMessage class represents one message sent or received over the D-Bus bus.
Definition: qdbusmessage.h:59
MessageType type() const
Returns the message type.
static bool invokeMethod(QObject *obj, const char *member, Qt::ConnectionType, QGenericReturnArgument ret, QGenericArgument val0=QGenericArgument(0), QGenericArgument val1=QGenericArgument(), QGenericArgument val2=QGenericArgument(), QGenericArgument val3=QGenericArgument(), QGenericArgument val4=QGenericArgument(), QGenericArgument val5=QGenericArgument(), QGenericArgument val6=QGenericArgument(), QGenericArgument val7=QGenericArgument(), QGenericArgument val8=QGenericArgument(), QGenericArgument val9=QGenericArgument())
Invokes the member (a signal or a slot name) on the object obj.
static QByteArray memberName(const QMetaMethod &member)
void setArguments(const QList< QVariant > &arguments)
Sets the arguments that are going to be sent over D-Bus to arguments.
static QDBusConnection::ConnectionCapabilities connectionCapabilies(DBusConnection *connection)
QMetaMethod method(int index) const
Returns the meta-data for the method with the given index.
static void qDBusRemoveWatch(DBusWatch *watch, void *data)
const_iterator ConstIterator
Qt-style synonym for QVector::const_iterator.
Definition: qvector.h:279
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421
bool isEmpty() const
Returns true if the vector has size 0; otherwise returns false.
Definition: qvector.h:139
static QDBusMessage makeLocalReply(const QDBusConnectionPrivate &conn, const QDBusMessage &asSent)
const char * signature() const
Returns the signature of this method (e.g., setValue(double)).
iterator find(const Key &key)
Returns an iterator pointing to the item with the key in the hash.
Definition: qhash.h:865
QThread * thread() const
Returns the thread in which the object lives.
Definition: qobject.cpp:1419
Access access() const
Returns the access specification of this method (private, protected, or public).
QDBusConnectionInterface * busService
iterator insertMulti(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition: qhash.h:772
QWaitCondition waitForFinishedCondition
static void cleanupDeletedNodes(QDBusConnectionPrivate::ObjectTreeNode &parent)
static dbus_bool_t qDBusAddTimeout(DBusTimeout *timeout, void *data)
bool activateInternalFilters(const ObjectTreeNode &node, const QDBusMessage &msg)
static const KeyPair *const end
static void huntAndDestroy(QObject *needle, QDBusConnectionPrivate::ObjectTreeNode &haystack)
QDebug & space()
Writes a space character to the debug stream and returns a reference to the stream.
Definition: qdebug.h:91
The QEvent class is the base class of all event classes.
Definition: qcoreevent.h:56
Type type() const
Returns the event type.
Definition: qcoreevent.h:303
#define qPrintable(string)
Definition: qglobal.h:1750
The QThread class provides a platform-independent way to manage threads.
Definition: qthread.h:59
void registerService(const QString &serviceName)
QDataStream & operator<<(QDataStream &out, const QUrl &url)
Writes url url to the stream out and returns a reference to the stream.
Definition: qurl.cpp:6757
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
Q_OUTOFLINE_TEMPLATE void qDeleteAll(ForwardIterator begin, ForwardIterator end)
Definition: qalgorithms.h:319
int methodCount() const
Returns the number of methods known to the meta-object system in this class, including the number of ...
QList< Key > keys() const
Returns a list containing all the keys in the hash, in an arbitrary order.
Definition: qhash.h:648
void deleteLater()
Schedules this object for deletion.
Definition: qobject.cpp:2145
static void reportThreadAction(int, int, QDBusConnectionPrivate *)
iterator erase(iterator it)
Removes the (key, value) pair associated with the iterator pos from the hash, and returns an iterator...
Definition: qhash.h:827
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
QString getNameOwner(const QString &service)
The QMetaMethod class provides meta-data about a member function.
Definition: qmetaobject.h:56
void setConnection(DBusConnection *connection, const QDBusErrorInternal &error)
int exec(ProcessEventsFlags flags=AllEvents)
Enters the main event loop and waits until exit() is called.
Definition: qeventloop.cpp:181
static DBusHandlerResult qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
#define enabled
friend class iterator
Definition: qhash.h:393
void(* QDBusSpyHook)(const QDBusMessage &)
iterator Iterator
Qt-style synonym for QHash::iterator.
Definition: qhash.h:473
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.
friend class const_iterator
Definition: qhash.h:461
void serverConnection(const QDBusConnection &connection)
int size() const
QDBusConnectionPrivate(QObject *parent=0)
void postEventToThread(int action, QObject *target, QEvent *event)
void customEvent(QEvent *e)
This event handler can be reimplemented in a subclass to receive custom events.
static QObject * findChildObject(const QDBusConnectionPrivate::ObjectTreeNode *root, const QString &fullpath, int start)
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:272
bool qDBusInitThreads()
void killTimer(int id)
Kills the timer with timer identifier, id.
Definition: qobject.cpp:1650
int removeAll(const T &t)
Removes all occurrences of value in the list and returns the number of entries removed.
Definition: qlist.h:770
int send(const QDBusMessage &message)
void reserve(int size)
QString message() const
Returns the message that the callee associated with this error.
Definition: qdbuserror.cpp:346