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