cd867c2f3a12595e7ee936473e32dec422b09a21
[profile/ivi/qtbase.git] / src / dbus / qdbusconnection.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtDBus module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include <qdebug.h>
43 #include <qcoreapplication.h>
44 #include <qstringlist.h>
45 #include <qthread.h>
46
47 #include "qdbusconnection.h"
48 #include "qdbusconnectioninterface.h"
49 #include "qdbuserror.h"
50 #include "qdbusmessage.h"
51 #include "qdbusmessage_p.h"
52 #include "qdbusconnection_p.h"
53 #include "qdbusinterface_p.h"
54 #include "qdbusutil_p.h"
55 #include "qdbusconnectionmanager_p.h"
56
57 #include "qdbusthreaddebug_p.h"
58
59 #include <algorithm>
60
61 #ifndef QT_NO_DBUS
62
63 QT_BEGIN_NAMESPACE
64
65 Q_GLOBAL_STATIC(QDBusConnectionManager, _q_manager)
66
67 QDBusConnectionPrivate *QDBusConnectionManager::sender() const
68 {
69     QMutexLocker locker(&senderMutex);
70     return connection(senderName);
71 }
72
73 void QDBusConnectionManager::setSender(const QDBusConnectionPrivate *s)
74 {
75     QMutexLocker locker(&senderMutex);
76     senderName = (s ? s->name : QString());
77 }
78
79 QDBusConnectionPrivate *QDBusConnectionManager::connection(const QString &name) const
80 {
81     return connectionHash.value(name, 0);
82 }
83
84 void QDBusConnectionManager::removeConnection(const QString &name)
85 {
86     QDBusConnectionPrivate *d = 0;
87     d = connectionHash.take(name);
88     if (d && !d->ref.deref())
89         d->deleteYourself();
90
91     // Static objects may be keeping the connection open.
92     // However, it is harmless to have outstanding references to a connection that is
93     // closing as long as those references will be soon dropped without being used.
94
95     // ### Output a warning if connections are being used after they have been removed.
96 }
97
98 QDBusConnectionManager::~QDBusConnectionManager()
99 {
100     for (QHash<QString, QDBusConnectionPrivate *>::const_iterator it = connectionHash.constBegin();
101          it != connectionHash.constEnd(); ++it) {
102         QDBusConnectionPrivate *d = it.value();
103         if (!d->ref.deref())
104             d->deleteYourself();
105         else
106             d->closeConnection();
107     }
108     connectionHash.clear();
109 }
110
111 QDBusConnectionManager* QDBusConnectionManager::instance()
112 {
113     return _q_manager();
114 }
115
116 Q_DBUS_EXPORT void qDBusBindToApplication();
117 void qDBusBindToApplication()
118 {
119 }
120
121 void QDBusConnectionManager::setConnection(const QString &name, QDBusConnectionPrivate *c)
122 {
123     connectionHash[name] = c;
124     c->name = name;
125 }
126
127 /*!
128     \class QDBusConnection
129     \inmodule QtDBus
130     \since 4.2
131
132     \brief The QDBusConnection class represents a connection to the D-Bus bus daemon.
133
134     This class is the initial point in a D-Bus session. Using it, you
135     can get access to remote objects, interfaces; connect remote
136     signals to your object's slots; register objects, etc.
137
138     D-Bus connections are created using the connectToBus() function,
139     which opens a connection to the server daemon and does the initial
140     handshaking, associating that connection with a name. Further
141     attempts to connect using the same name will return the same
142     connection.
143
144     The connection is then torn down using the disconnectFromBus()
145     function.
146
147     Once disconnected, calling connectToBus() will not reestablish a
148     connection, you must create a new QDBusConnection instance.
149
150     As a convenience for the two most common connection types, the
151     sessionBus() and systemBus() functions return open connections to
152     the session server daemon and the system server daemon,
153     respectively. Those connections are opened when first used and are
154     closed when the QCoreApplication destructor is run.
155
156     D-Bus also supports peer-to-peer connections, without the need for
157     a bus server daemon. Using this facility, two applications can
158     talk to each other and exchange messages. This can be achieved by
159     passing an address to connectToBus() function, which was opened by
160     another D-Bus application using QDBusServer.
161 */
162
163 /*!
164     \enum QDBusConnection::BusType
165     Specifies the type of the bus connection. The valid bus types are:
166
167     \value SessionBus           the session bus, associated with the running desktop session
168     \value SystemBus            the system bus, used to communicate with system-wide processes
169     \value ActivationBus        the activation bus, the "alias" for the bus that started the
170                                 service
171
172     On the Session Bus, one can find other applications by the same user that are sharing the same
173     desktop session (hence the name). On the System Bus, however, processes shared for the whole
174     system are usually found.
175 */
176
177 /*!
178     \enum QDBusConnection::RegisterOption
179     Specifies the options for registering objects with the connection. The possible values are:
180
181     \value ExportAdaptors                       export the contents of adaptors found in this object
182
183     \value ExportScriptableSlots                export this object's scriptable slots
184     \value ExportScriptableSignals              export this object's scriptable signals
185     \value ExportScriptableProperties           export this object's scriptable properties
186     \value ExportScriptableInvokables           export this object's scriptable invokables
187     \value ExportScriptableContents             shorthand form for ExportScriptableSlots |
188                                                 ExportScriptableSignals |
189                                                 ExportScriptableProperties
190
191     \value ExportNonScriptableSlots             export this object's non-scriptable slots
192     \value ExportNonScriptableSignals           export this object's non-scriptable signals
193     \value ExportNonScriptableProperties        export this object's non-scriptable properties
194     \value ExportNonScriptableInvokables        export this object's non-scriptable invokables
195     \value ExportNonScriptableContents          shorthand form for ExportNonScriptableSlots |
196                                                 ExportNonScriptableSignals |
197                                                 ExportNonScriptableProperties
198
199     \value ExportAllSlots                       export all of this object's slots
200     \value ExportAllSignals                     export all of this object's signals
201     \value ExportAllProperties                  export all of this object's properties
202     \value ExportAllInvokables                  export all of this object's invokables
203     \value ExportAllContents                    export all of this object's contents
204     \value ExportChildObjects                   export this object's child objects
205
206     \sa registerObject(), QDBusAbstractAdaptor, {usingadaptors.html}{Using adaptors}
207 */
208
209 /*!
210     \internal
211     \since 4.8
212     \enum QDBusConnection::VirtualObjectRegisterOption
213     Specifies the options for registering virtual objects with the connection. The possible values are:
214
215     \value SingleNode                           register a virtual object to handle one path only
216     \value SubPath                              register a virtual object so that it handles all sub paths
217
218     \sa registerVirtualObject(), QDBusVirtualObject
219 */
220
221 /*!
222     \enum QDBusConnection::UnregisterMode
223     The mode for unregistering an object path:
224
225     \value UnregisterNode       unregister this node only: do not unregister child objects
226     \value UnregisterTree       unregister this node and all its sub-tree
227
228     Note, however, if this object was registered with the ExportChildObjects option, UnregisterNode
229     will unregister the child objects too.
230 */
231
232 /*!
233     \since 4.8
234     \enum QDBusConnection::ConnectionCapability
235
236     This enum describes the available capabilities for a D-Bus connection.
237
238     \value UnixFileDescriptorPassing        enables passing of Unix file descriptors to other processes
239                                             (see QDBusUnixFileDescriptor)
240
241     \sa connectionCapabilities()
242 */
243
244 /*!
245     Creates a QDBusConnection object attached to the connection with name \a name.
246
247     This does not open the connection. You have to call connectToBus() to open it.
248 */
249 QDBusConnection::QDBusConnection(const QString &name)
250 {
251     if (name.isEmpty()) {
252         d = 0;
253     } else {
254         QMutexLocker locker(&_q_manager()->mutex);
255         d = _q_manager()->connection(name);
256         if (d)
257             d->ref.ref();
258     }
259 }
260
261 /*!
262     Creates a copy of the \a other connection.
263 */
264 QDBusConnection::QDBusConnection(const QDBusConnection &other)
265 {
266     d = other.d;
267     if (d)
268         d->ref.ref();
269 }
270
271 /*!
272   \internal
273    Creates a connection object with the given \a dd as private object.
274 */
275 QDBusConnection::QDBusConnection(QDBusConnectionPrivate *dd)
276 {
277     d = dd;
278     if (d)
279         d->ref.ref();
280 }
281
282 /*!
283     Disposes of this object. This does not close the connection: you
284     have to call disconnectFromBus() to do that.
285 */
286 QDBusConnection::~QDBusConnection()
287 {
288     if (d && !d->ref.deref())
289         d->deleteYourself();
290 }
291
292 /*!
293     Creates a copy of the connection \a other in this object. Note
294     that the connection this object referenced before the copy, is not
295     spontaneously disconnected.
296
297     \sa disconnectFromBus()
298 */
299 QDBusConnection &QDBusConnection::operator=(const QDBusConnection &other)
300 {
301     if (other.d)
302         other.d->ref.ref();
303     if (d && !d->ref.deref())
304         d->deleteYourself();
305     d = other.d;
306     return *this;
307 }
308
309 /*!
310     Opens a connection of type \a type to one of the known busses and
311     associate with it the connection name \a name. Returns a
312     QDBusConnection object associated with that connection.
313 */
314 QDBusConnection QDBusConnection::connectToBus(BusType type, const QString &name)
315 {
316 //    Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
317 //               "Cannot create connection without a Q[Core]Application instance");
318     if (!qdbus_loadLibDBus()) {
319         QDBusConnectionPrivate *d = 0;
320         return QDBusConnection(d);
321     }
322
323     QMutexLocker locker(&_q_manager()->mutex);
324
325     QDBusConnectionPrivate *d = _q_manager()->connection(name);
326     if (d || name.isEmpty())
327         return QDBusConnection(d);
328
329     d = new QDBusConnectionPrivate;
330     DBusConnection *c = 0;
331     QDBusErrorInternal error;
332     switch (type) {
333         case SystemBus:
334             c = q_dbus_bus_get_private(DBUS_BUS_SYSTEM, error);
335             break;
336         case SessionBus:
337             c = q_dbus_bus_get_private(DBUS_BUS_SESSION, error);
338             break;
339         case ActivationBus:
340             c = q_dbus_bus_get_private(DBUS_BUS_STARTER, error);
341             break;
342     }
343     d->setConnection(c, error); //setConnection does the error handling for us
344
345     _q_manager()->setConnection(name, d);
346
347     QDBusConnection retval(d);
348
349     // create the bus service
350     // will lock in QDBusConnectionPrivate::connectRelay()
351     d->setBusService(retval);
352
353     return retval;
354 }
355
356 /*!
357     Opens a connection to a private bus on address \a address and associate with it the
358     connection name \a name. Returns a QDBusConnection object associated with that connection.
359 */
360 QDBusConnection QDBusConnection::connectToBus(const QString &address,
361                                               const QString &name)
362 {
363 //    Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
364 //               "Cannot create connection without a Q[Core]Application instance");
365     if (!qdbus_loadLibDBus()) {
366         QDBusConnectionPrivate *d = 0;
367         return QDBusConnection(d);
368     }
369
370     QMutexLocker locker(&_q_manager()->mutex);
371
372     QDBusConnectionPrivate *d = _q_manager()->connection(name);
373     if (d || name.isEmpty())
374         return QDBusConnection(d);
375
376     d = new QDBusConnectionPrivate;
377     // setConnection does the error handling for us
378     QDBusErrorInternal error;
379     DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
380     if (c) {
381         if (!q_dbus_bus_register(c, error)) {
382             q_dbus_connection_unref(c);
383             c = 0;
384         }
385     }
386     d->setConnection(c, error);
387     _q_manager()->setConnection(name, d);
388
389     QDBusConnection retval(d);
390
391     // create the bus service
392     // will lock in QDBusConnectionPrivate::connectRelay()
393     d->setBusService(retval);
394
395     return retval;
396 }
397 /*!
398     \since 4.8
399
400     Opens a peer-to-peer connection on address \a address and associate with it the
401     connection name \a name. Returns a QDBusConnection object associated with that connection.
402 */
403 QDBusConnection QDBusConnection::connectToPeer(const QString &address,
404                                                const QString &name)
405 {
406 //    Q_ASSERT_X(QCoreApplication::instance(), "QDBusConnection::addConnection",
407 //               "Cannot create connection without a Q[Core]Application instance");
408     if (!qdbus_loadLibDBus()) {
409         QDBusConnectionPrivate *d = 0;
410         return QDBusConnection(d);
411     }
412
413     QMutexLocker locker(&_q_manager()->mutex);
414
415     QDBusConnectionPrivate *d = _q_manager()->connection(name);
416     if (d || name.isEmpty())
417         return QDBusConnection(d);
418
419     d = new QDBusConnectionPrivate;
420     // setPeer does the error handling for us
421     QDBusErrorInternal error;
422     DBusConnection *c = q_dbus_connection_open_private(address.toUtf8().constData(), error);
423
424     d->setPeer(c, error);
425     _q_manager()->setConnection(name, d);
426
427     QDBusConnection retval(d);
428
429     return retval;
430 }
431
432 /*!
433     Closes the bus connection of name \a name.
434
435     Note that if there are still QDBusConnection objects associated
436     with the same connection, the connection will not be closed until
437     all references are dropped. However, no further references can be
438     created using the QDBusConnection constructor.
439 */
440 void QDBusConnection::disconnectFromBus(const QString &name)
441 {
442     if (_q_manager()) {
443         QMutexLocker locker(&_q_manager()->mutex);
444         QDBusConnectionPrivate *d = _q_manager()->connection(name);
445         if (d && d->mode != QDBusConnectionPrivate::ClientMode)
446             return;
447         _q_manager()->removeConnection(name);
448     }
449 }
450
451 /*!
452     \since 4.8
453
454     Closes the peer connection of name \a name.
455
456     Note that if there are still QDBusConnection objects associated
457     with the same connection, the connection will not be closed until
458     all references are dropped. However, no further references can be
459     created using the QDBusConnection constructor.
460 */
461 void QDBusConnection::disconnectFromPeer(const QString &name)
462 {
463     if (_q_manager()) {
464         QMutexLocker locker(&_q_manager()->mutex);
465         QDBusConnectionPrivate *d = _q_manager()->connection(name);
466         if (d && d->mode != QDBusConnectionPrivate::PeerMode)
467             return;
468         _q_manager()->removeConnection(name);
469     }
470 }
471
472 /*!
473     Sends the \a message over this connection, without waiting for a
474     reply. This is suitable for errors, signals, and return values as
475     well as calls whose return values are not necessary.
476
477     Returns true if the message was queued successfully, false otherwise.
478 */
479 bool QDBusConnection::send(const QDBusMessage &message) const
480 {
481     if (!d || !d->connection) {
482         QDBusError err = QDBusError(QDBusError::Disconnected,
483                                     QLatin1String("Not connected to D-BUS server"));
484         if (d)
485             d->lastError = err;
486         return false;
487     }
488     return d->send(message) != 0;
489 }
490
491 /*!
492     Sends the \a message over this connection and returns immediately.
493     When the reply is received, the method \a returnMethod is called in
494     the \a receiver object. If an error occurs, the method \a errorMethod
495     will be called instead.
496
497     If no reply is received within \a timeout milliseconds, an automatic
498     error will be delivered indicating the expiration of the call.
499     The default \a timeout is -1, which will be replaced with an
500     implementation-defined value that is suitable for inter-process
501     communications (generally, 25 seconds).
502
503     This function is suitable for method calls only. It is guaranteed
504     that the slot will be called exactly once with the reply, as long
505     as the parameter types match and no error occurs.
506
507     Returns true if the message was sent, or false if the message could
508     not be sent.
509 */
510 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
511                                        const char *returnMethod, const char *errorMethod,
512                                        int timeout) const
513 {
514     if (!d || !d->connection) {
515         QDBusError err = QDBusError(QDBusError::Disconnected,
516                                     QLatin1String("Not connected to D-BUS server"));
517         if (d)
518             d->lastError = err;
519         return false;
520     }
521     return d->sendWithReplyAsync(message, receiver, returnMethod, errorMethod, timeout) != 0;
522 }
523
524 /*!
525     \overload
526     \deprecated
527     Sends the \a message over this connection and returns immediately.
528     When the reply is received, the method \a returnMethod is called in
529     the \a receiver object.
530
531     This function is suitable for method calls only. It is guaranteed
532     that the slot will be called exactly once with the reply, as long
533     as the parameter types match and no error occurs.
534
535     This function is dangerous because it cannot report errors, including
536     the expiration of the timeout.
537
538     Returns true if the message was sent, or false if the message could
539     not be sent.
540 */
541 bool QDBusConnection::callWithCallback(const QDBusMessage &message, QObject *receiver,
542                                        const char *returnMethod, int timeout) const
543 {
544     return callWithCallback(message, receiver, returnMethod, 0, timeout);
545 }
546
547 /*!
548     Sends the \a message over this connection and blocks, waiting for
549     a reply, for at most \a timeout milliseconds. This function is
550     suitable for method calls only. It returns the reply message as
551     its return value, which will be either of type
552     QDBusMessage::ReplyMessage or QDBusMessage::ErrorMessage.
553
554     If no reply is received within \a timeout milliseconds, an automatic
555     error will be delivered indicating the expiration of the call.
556     The default \a timeout is -1, which will be replaced with an
557     implementation-defined value that is suitable for inter-process
558     communications (generally, 25 seconds).
559
560     See the QDBusInterface::call() function for a more friendly way
561     of placing calls.
562
563     \warning If \a mode is QDBus::BlockWithGui, this function will
564              reenter the Qt event loop in order to wait for the
565              reply. During the wait, it may deliver signals and other
566              method calls to your application. Therefore, it must be
567              prepared to handle a reentrancy whenever a call is
568              placed with call().
569 */
570 QDBusMessage QDBusConnection::call(const QDBusMessage &message, QDBus::CallMode mode, int timeout) const
571 {
572     if (!d || !d->connection) {
573         QDBusError err = QDBusError(QDBusError::Disconnected,
574                                     QLatin1String("Not connected to D-Bus server"));
575         if (d)
576             d->lastError = err;
577
578         return QDBusMessage::createError(err);
579     }
580
581     if (mode != QDBus::NoBlock)
582         return d->sendWithReply(message, mode, timeout);
583
584     d->send(message);
585     QDBusMessage retval;
586     retval << QVariant(); // add one argument (to avoid .at(0) problems)
587     return retval;
588 }
589
590 /*!
591     \since 4.5
592     Sends the \a message over this connection and returns
593     immediately. This function is suitable for method calls only. It
594     returns an object of type QDBusPendingCall which can be used to
595     track the status of the reply.
596
597     If no reply is received within \a timeout milliseconds, an automatic
598     error will be delivered indicating the expiration of the call. The
599     default \a timeout is -1, which will be replaced with an
600     implementation-defined value that is suitable for inter-process
601     communications (generally, 25 seconds). This timeout is also the
602     upper limit for waiting in QDBusPendingCall::waitForFinished().
603
604     See the QDBusInterface::asyncCall() function for a more friendly way
605     of placing calls.
606 */
607 QDBusPendingCall QDBusConnection::asyncCall(const QDBusMessage &message, int timeout) const
608 {
609     if (!d || !d->connection) {
610         return QDBusPendingCall(0); // null pointer -> disconnected
611     }
612
613     QDBusPendingCallPrivate *priv = d->sendWithReplyAsync(message, timeout);
614     return QDBusPendingCall(priv);
615 }
616
617 /*!
618     Connects the signal specified by the \a service, \a path, \a interface and \a name parameters to
619     the slot \a slot in object \a receiver. The arguments \a service and \a path can be empty,
620     denoting a connection to any signal of the (\a interface, \a name) pair, from any remote
621     application.
622
623     Returns true if the connection was successful.
624
625     \warning The signal will only be delivered to the slot if the parameters match. This verification
626              can be done only when the signal is received, not at connection time.
627 */
628 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
629                               const QString &name, QObject *receiver, const char *slot)
630 {
631     return connect(service, path, interface, name, QStringList(), QString(), receiver, slot);
632 }
633
634 /*!
635     \overload
636
637     Connects the signal to the slot \a slot in object \a
638     receiver. Unlike the previous connect() overload, this function
639     allows one to specify the parameter signature to be connected
640     using the \a signature variable. The function will then verify
641     that this signature can be delivered to the slot specified by \a
642     slot and return false otherwise.
643
644     Returns true if the connection was successful.
645
646     \note This function verifies that the signal signature matches the
647           slot's parameters, but it does not verify that the actual
648           signal exists with the given signature in the remote
649           service.
650 */
651 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
652                               const QString &name, const QString &signature,
653                               QObject *receiver, const char *slot)
654 {
655     return connect(service, path, interface, name, QStringList(), signature, receiver, slot);
656 }
657
658 /*!
659     \overload
660     \since 4.6
661
662     Connects the signal to the slot \a slot in object \a
663     receiver. Unlike the previous connect() overload, this function
664     allows one to specify the parameter signature to be connected
665     using the \a signature variable. The function will then verify
666     that this signature can be delivered to the slot specified by \a
667     slot and return false otherwise.
668
669     The \a argumentMatch parameter lists the string parameters to be matched,
670     in sequential order. Note that, to match an empty string, you need to
671     pass a QString that is empty but not null (i.e., QString("")). A null
672     QString skips matching at that position.
673
674     Returns true if the connection was successful.
675
676     \note This function verifies that the signal signature matches the
677           slot's parameters, but it does not verify that the actual
678           signal exists with the given signature in the remote
679           service.
680 */
681 bool QDBusConnection::connect(const QString &service, const QString &path, const QString& interface,
682                               const QString &name, const QStringList &argumentMatch, const QString &signature,
683                               QObject *receiver, const char *slot)
684 {
685
686     if (!receiver || !slot || !d || !d->connection)
687         return false;
688     if (interface.isEmpty() && name.isEmpty())
689         return false;
690     if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface)) {
691 #ifndef QT_NO_DEBUG
692         qWarning("QDBusConnection::connect: interface name '%s' is not valid", interface.toLatin1().constData());
693 #endif
694         return false;
695     }
696     if (!service.isEmpty() && !QDBusUtil::isValidBusName(service)) {
697 #ifndef QT_NO_DEBUG
698         qWarning("QDBusConnection::connect: service name '%s' is not valid", service.toLatin1().constData());
699 #endif
700         return false;
701     }
702     if (!path.isEmpty() && !QDBusUtil::isValidObjectPath(path)) {
703 #ifndef QT_NO_DEBUG
704         qWarning("QDBusConnection::connect: object path '%s' is not valid", path.toLatin1().constData());
705 #endif
706         return false;
707     }
708
709     QDBusWriteLocker locker(ConnectAction, d);
710     return d->connectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
711 }
712
713 /*!
714     Disconnects the signal specified by the \a service, \a path, \a interface
715     and \a name parameters from the slot \a slot in object \a receiver. The
716     arguments must be the same as passed to the connect() function.
717
718     Returns true if the disconnection was successful.
719 */
720 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString &interface,
721                                  const QString &name, QObject *receiver, const char *slot)
722 {
723     return disconnect(service, path, interface, name, QStringList(), QString(), receiver, slot);
724 }
725
726 /*!
727     \overload
728
729     Disconnects the signal specified by the \a service, \a path, \a
730     interface, \a name, and \a signature parameters from the slot \a slot in
731     object \a receiver. The arguments must be the same as passed to the
732     connect() function.
733
734     Returns true if the disconnection was successful.
735 */
736 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
737                                  const QString &name, const QString &signature,
738                                  QObject *receiver, const char *slot)
739 {
740     return disconnect(service, path, interface, name, QStringList(), signature, receiver, slot);
741 }
742
743 /*!
744     \overload
745     \since 4.6
746
747     Disconnects the signal specified by the \a service, \a path, \a
748     interface, \a name, \a argumentMatch, and \a signature parameters from
749     the slot \a slot in object \a receiver. The arguments must be the same as
750     passed to the connect() function.
751
752     Returns true if the disconnection was successful.
753 */
754 bool QDBusConnection::disconnect(const QString &service, const QString &path, const QString& interface,
755                                  const QString &name, const QStringList &argumentMatch, const QString &signature,
756                                  QObject *receiver, const char *slot)
757 {
758     if (!receiver || !slot || !d || !d->connection)
759         return false;
760     if (!interface.isEmpty() && !QDBusUtil::isValidInterfaceName(interface))
761         return false;
762     if (interface.isEmpty() && name.isEmpty())
763         return false;
764
765     QDBusWriteLocker locker(DisconnectAction, d);
766     return d->disconnectSignal(service, path, interface, name, argumentMatch, signature, receiver, slot);
767 }
768
769 /*!
770     Registers the object \a object at path \a path and returns true if
771     the registration was successful. The \a options parameter
772     specifies how much of the object \a object will be exposed through
773     D-Bus.
774
775     This function does not replace existing objects: if there is already an object registered at
776     path \a path, this function will return false. Use unregisterObject() to unregister it first.
777
778     You cannot register an object as a child object of an object that
779     was registered with QDBusConnection::ExportChildObjects.
780 */
781 bool QDBusConnection::registerObject(const QString &path, QObject *object, RegisterOptions options)
782 {
783     Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registerObject",
784                "Invalid object path given");
785     if (!d || !d->connection || !object || !options || !QDBusUtil::isValidObjectPath(path))
786         return false;
787
788     QStringList pathComponents = path.split(QLatin1Char('/'));
789     if (pathComponents.last().isEmpty())
790         pathComponents.removeLast();
791     QDBusWriteLocker locker(RegisterObjectAction, d);
792
793     // lower-bound search for where this object should enter in the tree
794     QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator node = &d->rootNode;
795     int i = 1;
796     while (node) {
797         if (pathComponents.count() == i) {
798             // this node exists
799             // consider it free if there's no object here and the user is not trying to
800             // replace the object sub-tree
801             if (node->obj)
802                 return false;
803
804             if (options & QDBusConnectionPrivate::VirtualObject) {
805                 // technically the check for children needs to go even deeper
806                 if (options & SubPath) {
807                     foreach (const QDBusConnectionPrivate::ObjectTreeNode &child, node->children) {
808                         if (child.obj)
809                             return false;
810                     }
811                 }
812             } else {
813                 if ((options & ExportChildObjects && !node->children.isEmpty()))
814                     return false;
815             }
816             // we can add the object here
817             node->obj = object;
818             node->flags = options;
819
820             d->registerObject(node);
821             //qDebug("REGISTERED FOR %s", path.toLocal8Bit().constData());
822             return true;
823         }
824
825         // if a virtual object occupies this path, return false
826         if (node->obj && (node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath)) {
827             qDebug("Cannot register object at %s because QDBusVirtualObject handles all sub-paths.",
828                    qPrintable(path));
829             return false;
830         }
831
832         // find the position where we'd insert the node
833         QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
834             std::lower_bound(node->children.begin(), node->children.end(), pathComponents.at(i));
835         if (it != node->children.end() && it->name == pathComponents.at(i)) {
836             // match: this node exists
837             node = it;
838
839             // are we allowed to go deeper?
840             if (node->flags & ExportChildObjects) {
841                 // we're not
842                 qDebug("Cannot register object at %s because %s exports its own child objects",
843                        qPrintable(path), qPrintable(pathComponents.at(i)));
844                 return false;
845             }
846         } else {
847             // add entry
848             node = node->children.insert(it, pathComponents.at(i));
849         }
850
851         // iterate
852         ++i;
853     }
854
855     Q_ASSERT_X(false, "QDBusConnection::registerObject", "The impossible happened");
856     return false;
857 }
858
859 /*!
860     \internal
861     \since 4.8
862     Registers a QDBusTreeNode for a path. It can handle a path including all child paths, thus
863     handling multiple DBus nodes.
864
865     To unregister a QDBusTreeNode use the unregisterObject() function with its path.
866 */
867 bool QDBusConnection::registerVirtualObject(const QString &path, QDBusVirtualObject *treeNode,
868                       VirtualObjectRegisterOption options)
869 {
870     int opts = options | QDBusConnectionPrivate::VirtualObject;
871     return registerObject(path, (QObject*) treeNode, (RegisterOptions) opts);
872 }
873
874 /*!
875     Unregisters an object that was registered with the registerObject() at the object path given by
876     \a path and, if \a mode is QDBusConnection::UnregisterTree, all of its sub-objects too.
877
878     Note that you cannot unregister objects that were not registered with registerObject().
879 */
880 void QDBusConnection::unregisterObject(const QString &path, UnregisterMode mode)
881 {
882     if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
883         return;
884
885     QStringList pathComponents = path.split(QLatin1Char('/'));
886     QDBusWriteLocker locker(UnregisterObjectAction, d);
887     QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
888     int i = 1;
889
890     // find the object
891     while (node) {
892         if (pathComponents.count() == i || !path.compare(QLatin1String("/"))) {
893             // found it
894             node->obj = 0;
895             node->flags = 0;
896
897             if (mode == UnregisterTree) {
898                 // clear the sub-tree as well
899                 node->children.clear();  // can't disconnect the objects because we really don't know if they can
900                                 // be found somewhere else in the path too
901             }
902
903             return;
904         }
905
906         QDBusConnectionPrivate::ObjectTreeNode::DataList::Iterator it =
907             std::lower_bound(node->children.begin(), node->children.end(), pathComponents.at(i));
908         if (it == node->children.end() || it->name != pathComponents.at(i))
909             break;              // node not found
910
911         node = it;
912         ++i;
913     }
914 }
915
916 /*!
917     Return the object that was registered with the registerObject() at the object path given by
918     \a path.
919 */
920 QObject *QDBusConnection::objectRegisteredAt(const QString &path) const
921 {
922     Q_ASSERT_X(QDBusUtil::isValidObjectPath(path), "QDBusConnection::registeredObject",
923                "Invalid object path given");
924     if (!d || !d->connection || !QDBusUtil::isValidObjectPath(path))
925         return 0;
926
927     QStringList pathComponents = path.split(QLatin1Char('/'));
928     if (pathComponents.last().isEmpty())
929         pathComponents.removeLast();
930
931     // lower-bound search for where this object should enter in the tree
932     QDBusReadLocker lock(ObjectRegisteredAtAction, d);
933     const QDBusConnectionPrivate::ObjectTreeNode *node = &d->rootNode;
934
935     int i = 1;
936     while (node) {
937         if (pathComponents.count() == i)
938             return node->obj;
939         if ((node->flags & QDBusConnectionPrivate::VirtualObject) && (node->flags & QDBusConnection::SubPath))
940             return node->obj;
941
942         QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it =
943             std::lower_bound(node->children.constBegin(), node->children.constEnd(), pathComponents.at(i));
944         if (it == node->children.constEnd() || it->name != pathComponents.at(i))
945             break;              // node not found
946
947         node = it;
948         ++i;
949     }
950     return 0;
951 }
952
953
954
955 /*!
956     Returns a QDBusConnectionInterface object that represents the
957     D-Bus server interface on this connection.
958 */
959 QDBusConnectionInterface *QDBusConnection::interface() const
960 {
961     if (!d)
962         return 0;
963     return d->busService;
964 }
965
966 /*!
967     \internal
968     \since 4.8
969
970     Returns the internal, implementation-defined pointer for this
971     connection. Currently, this returns a DBusConnection* pointer,
972     without changing the reference count. It is the responsibility of
973     the caller to call dbus_connection_ref if it wants to store the
974     pointer.
975 */
976 void *QDBusConnection::internalPointer() const
977 {
978     return d ? d->connection : 0;
979 }
980
981 /*!
982     Returns true if this QDBusConnection object is connected.
983 */
984 bool QDBusConnection::isConnected() const
985 {
986     return d && d->connection && q_dbus_connection_get_is_connected(d->connection);
987 }
988
989 /*!
990     Returns the last error that happened in this connection.
991
992     This function is provided for low-level code. If you're using
993     QDBusInterface::call(), error codes are reported by its return
994     value.
995
996     \sa QDBusInterface, QDBusMessage
997 */
998 QDBusError QDBusConnection::lastError() const
999 {
1000     return d ? d->lastError : QDBusError();
1001 }
1002
1003 /*!
1004     Returns the unique connection name for this connection, if this QDBusConnection object is
1005     connected, or an empty QString otherwise.
1006
1007     A Unique Connection Name is a string in the form ":x.xxx" (where x
1008     are decimal digits) that is assigned by the D-Bus server daemon
1009     upon connection. It uniquely identifies this client in the bus.
1010
1011     This function returns an empty QString for peer-to-peer connections.
1012 */
1013 QString QDBusConnection::baseService() const
1014 {
1015     return d ? d->baseService : QString();
1016 }
1017
1018 /*!
1019     \since 4.5
1020
1021     Returns the connection name for this connection, as given as the
1022     name parameter to connectToBus().
1023
1024     The connection name can be used to uniquely identify actual
1025     underlying connections to buses.  Copies made from a single
1026     connection will always implicitly share the underlying connection,
1027     and hence will have the same connection name.
1028
1029     Inversely, two connections having different connection names will
1030     always either be connected to different buses, or have a different
1031     unique name (as returned by baseService()) on that bus.
1032
1033     \sa connectToBus(), disconnectFromBus()
1034 */
1035 QString QDBusConnection::name() const
1036 {
1037     return d ? d->name : QString();
1038 }
1039
1040 /*!
1041     \since 4.8
1042
1043     Returns the capabilities of this connection as negotiated with the bus
1044     server or peer. If this QDBusConnection is not connected, this function
1045     returns no capabilities.
1046 */
1047 QDBusConnection::ConnectionCapabilities QDBusConnection::connectionCapabilities() const
1048 {
1049     return d ? d->capabilities : ConnectionCapabilities(0);
1050 }
1051
1052 /*!
1053     Attempts to register the \a serviceName on the D-Bus server and
1054     returns true if the registration succeeded. The registration will
1055     fail if the name is already registered by another application.
1056
1057     \sa unregisterService(), QDBusConnectionInterface::registerService()
1058 */
1059 bool QDBusConnection::registerService(const QString &serviceName)
1060 {
1061     if (interface() && interface()->registerService(serviceName)) {
1062         if (d) d->registerService(serviceName);
1063         return true;
1064     }
1065     return false;
1066 }
1067
1068 /*!
1069     Unregisters the service \a serviceName that was previously
1070     registered with registerService() and returns true if it
1071     succeeded.
1072
1073     \sa registerService(), QDBusConnectionInterface::unregisterService()
1074 */
1075 bool QDBusConnection::unregisterService(const QString &serviceName)
1076 {
1077     if (interface()->unregisterService(serviceName)) {
1078         if (d) d->unregisterService(serviceName);
1079         return true;
1080     }
1081     return false;
1082 }
1083
1084 static const char _q_sessionBusName[] = "qt_default_session_bus";
1085 static const char _q_systemBusName[] = "qt_default_system_bus";
1086
1087 class QDBusDefaultConnection: public QDBusConnection
1088 {
1089     const char *ownName;
1090 public:
1091     inline QDBusDefaultConnection(BusType type, const char *name)
1092         : QDBusConnection(connectToBus(type, QString::fromLatin1(name))), ownName(name)
1093     {
1094         // make sure this connection is running on the main thread
1095         QCoreApplication *instance = QCoreApplication::instance();
1096         if (!instance) {
1097             qWarning("QDBusConnection: %s D-Bus connection created before QCoreApplication. Application may misbehave.",
1098                      type == SessionBus ? "session" : type == SystemBus ? "system" : "generic");
1099         } else if (QDBusConnectionPrivate::d(*this)) {
1100             QDBusConnectionPrivate::d(*this)->moveToThread(instance->thread());
1101         }
1102     }
1103
1104     inline ~QDBusDefaultConnection()
1105     { disconnectFromBus(QString::fromLatin1(ownName)); }
1106 };
1107
1108 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_sessionBus,
1109                           (QDBusConnection::SessionBus, _q_sessionBusName))
1110 Q_GLOBAL_STATIC_WITH_ARGS(QDBusDefaultConnection, _q_systemBus,
1111                           (QDBusConnection::SystemBus, _q_systemBusName))
1112
1113 /*!
1114     \fn QDBusConnection QDBusConnection::sessionBus()
1115
1116     Returns a QDBusConnection object opened with the session bus. The object
1117     reference returned by this function is valid until the application terminates,
1118     at which point the connection will be closed and the object deleted.
1119 */
1120 QDBusConnection QDBusConnection::sessionBus()
1121 {
1122     return *_q_sessionBus();
1123 }
1124
1125 /*!
1126     \fn QDBusConnection QDBusConnection::systemBus()
1127
1128     Returns a QDBusConnection object opened with the system bus. The object reference returned
1129     by this function is valid until the QCoreApplication's destructor is run, when the
1130     connection will be closed and the object, deleted.
1131 */
1132 QDBusConnection QDBusConnection::systemBus()
1133 {
1134     return *_q_systemBus();
1135 }
1136
1137 /*!
1138   \nonreentrant
1139
1140   Returns the connection that sent the signal, if called in a slot activated
1141   by QDBus; otherwise it returns 0.
1142
1143   \note Please avoid this function. This function is not thread-safe, so if
1144   there's any other thread delivering a D-Bus call, this function may return
1145   the wrong connection. In new code, please use QDBusContext::connection()
1146   (see that class for a description on how to use it).
1147 */
1148 QDBusConnection QDBusConnection::sender()
1149 {
1150     return QDBusConnection(_q_manager()->sender());
1151 }
1152
1153 /*!
1154   \internal
1155 */
1156 void QDBusConnectionPrivate::setSender(const QDBusConnectionPrivate *s)
1157 {
1158     _q_manager()->setSender(s);
1159 }
1160
1161 /*!
1162   \internal
1163 */
1164 void QDBusConnectionPrivate::setBusService(const QDBusConnection &connection)
1165 {
1166     busService = new QDBusConnectionInterface(connection, this);
1167     ref.deref(); // busService has increased the refcounting to us
1168                  // avoid cyclic refcounting
1169
1170     QObject::connect(this, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1171                      busService, SIGNAL(callWithCallbackFailed(QDBusError,QDBusMessage)),
1172                      Qt::QueuedConnection);
1173 }
1174
1175 /*!
1176     \since 4.8
1177     Returns the local machine ID as known to the D-Bus system. Each
1178     node or host that runs D-Bus has a unique identifier that can be
1179     used to distinguish it from other hosts if they are sharing
1180     resources like the filesystem.
1181
1182     Note that the local machine ID is not guaranteed to be persistent
1183     across boots of the system, so this identifier should not be
1184     stored in persistent storage (like the filesystem). It is
1185     guaranteed to remain constant only during the lifetime of this
1186     boot session.
1187 */
1188 QByteArray QDBusConnection::localMachineId()
1189 {
1190     char *dbus_machine_id = q_dbus_get_local_machine_id();
1191     QByteArray result = dbus_machine_id;
1192     q_dbus_free(dbus_machine_id);
1193     return result;
1194 }
1195
1196 /*!
1197     \namespace QDBus
1198     \inmodule QtDBus
1199
1200     \brief The QDBus namespace contains miscellaneous identifiers used
1201     throughout the QtDBus library.
1202 */
1203
1204 /*!
1205     \enum QDBus::CallMode
1206
1207     This enum describes the various ways of placing a function call. The valid modes are:
1208
1209     \value NoBlock              Place the call but don't wait for the reply (the reply's contents
1210                                 will be discarded).
1211     \value Block                Don't use an event loop to wait for a reply, but instead block on
1212                                 network operations while waiting. This means the
1213                                 user-interface may not be updated until the function returns.
1214     \value BlockWithGui         Use the Qt event loop to wait for a reply. This means that the
1215                                 user-interface will stay responsive (processing input events),
1216                                 but it also means other events may happen, like signal delivery
1217                                 and other D-Bus method calls.
1218     \value AutoDetect           Automatically detect if the called function has a reply.
1219
1220     When using BlockWithGui, applications must be prepared for reentrancy in any function.
1221 */
1222
1223 QT_END_NAMESPACE
1224
1225 #endif // QT_NO_DBUS