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