1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Copyright (C) 2016 Intel Corporation.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtDBus module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41//
42// W A R N I N G
43// -------------
44//
45// This file is not part of the public API. This header file may
46// change from version to version without notice, or even be
47// removed.
48//
49// We mean it.
50//
51//
52
53#ifndef QDBUSCONNECTION_P_H
54#define QDBUSCONNECTION_P_H
55
56#include <QtDBus/private/qtdbusglobal_p.h>
57#include <qdbuserror.h>
58#include <qdbusconnection.h>
59
60#include <QtCore/qatomic.h>
61#include <QtCore/qhash.h>
62#include <QtCore/qlist.h>
63#include <QtCore/qobject.h>
64#include <QtCore/qpointer.h>
65#include <QtCore/qreadwritelock.h>
66#include <QtCore/qstringlist.h>
67#include <QtCore/qvarlengtharray.h>
68
69#include "qdbus_symbols_p.h"
70
71#include <qdbusmessage.h>
72#include <qdbusservicewatcher.h> // for the WatchMode enum
73Q_MOC_INCLUDE(<QtDBus/private/qdbuspendingcall_p.h>)
74
75#ifndef QT_NO_DBUS
76
77QT_BEGIN_NAMESPACE
78
79class QDBusMessage;
80class QSocketNotifier;
81class QTimerEvent;
82class QDBusObjectPrivate;
83class QDBusCallDeliveryEvent;
84class QDBusActivateObjectEvent;
85class QMetaMethod;
86class QDBusInterfacePrivate;
87struct QDBusMetaObject;
88class QDBusAbstractInterface;
89class QDBusConnectionInterface;
90class QDBusPendingCallPrivate;
91class QDBusServer;
92
93#ifndef QT_BOOTSTRAPPED
94
95class QDBusErrorInternal
96{
97 mutable DBusError error;
98 Q_DISABLE_COPY_MOVE(QDBusErrorInternal)
99public:
100 inline QDBusErrorInternal() { q_dbus_error_init(&error); }
101 inline ~QDBusErrorInternal() { q_dbus_error_free(&error); }
102 inline bool operator !() const { return !q_dbus_error_is_set(&error); }
103 inline operator DBusError *() { q_dbus_error_free(&error); return &error; }
104 inline operator QDBusError() const { QDBusError err(&error); q_dbus_error_free(&error); return err; }
105};
106
107// QDBusConnectionPrivate holds the DBusConnection and
108// can have many QDBusConnection objects referring to it
109
110class Q_AUTOTEST_EXPORT QDBusConnectionPrivate: public QObject
111{
112 Q_OBJECT
113public:
114 // structs and enums
115 enum ConnectionMode { InvalidMode, ServerMode, ClientMode, PeerMode }; // LocalMode
116
117 struct Watcher
118 {
119 Watcher(): watch(nullptr), read(nullptr), write(nullptr) {}
120 DBusWatch *watch;
121 QSocketNotifier *read;
122 QSocketNotifier *write;
123 };
124
125 struct ArgMatchRules {
126 QStringList args;
127 QString arg0namespace;
128 bool operator==(const ArgMatchRules &other) const {
129 return args == other.args &&
130 arg0namespace == other.arg0namespace;
131 }
132 };
133
134 struct SignalHook
135 {
136 inline SignalHook() : obj(nullptr), midx(-1) { }
137 QString service, path, signature;
138 QObject* obj;
139 int midx;
140 QList<QMetaType> params;
141 ArgMatchRules argumentMatch;
142 QByteArray matchRule;
143 };
144
145 enum TreeNodeType {
146 Object = 0x0,
147 VirtualObject = 0x01000000
148 };
149
150 struct ObjectTreeNode
151 {
152 typedef QList<ObjectTreeNode> DataList;
153
154 inline ObjectTreeNode() : obj(nullptr), flags(0) { }
155 inline ObjectTreeNode(const QString &n) // intentionally implicit
156 : name(n), obj(nullptr), flags(0) { }
157 inline bool operator<(const QString &other) const
158 { return name < other; }
159 inline bool operator<(QStringView other) const
160 { return name < other; }
161 inline bool isActive() const
162 { return obj || !children.isEmpty(); }
163
164 QString name;
165 QString interfaceName;
166 union {
167 QObject *obj;
168 QDBusVirtualObject *treeNode;
169 };
170 int flags;
171
172 DataList children;
173 };
174
175public:
176 // typedefs
177 typedef QMultiHash<qintptr, Watcher> WatcherHash;
178 typedef QHash<int, DBusTimeout *> TimeoutHash;
179 typedef QList<QDBusMessage> PendingMessageList;
180
181 typedef QMultiHash<QString, SignalHook> SignalHookHash;
182 typedef QHash<QString, QDBusMetaObject* > MetaObjectHash;
183 typedef QHash<QByteArray, int> MatchRefCountHash;
184 typedef QList<QDBusPendingCallPrivate *> PendingCallList;
185
186 struct WatchedServiceData {
187 WatchedServiceData() : refcount(0) {}
188 WatchedServiceData(const QString &owner, int refcount = 0)
189 : owner(owner), refcount(refcount)
190 {}
191 QString owner;
192 int refcount;
193 };
194 typedef QHash<QString, WatchedServiceData> WatchedServicesHash;
195
196public:
197 // public methods are entry points from other objects
198 explicit QDBusConnectionPrivate(QObject *parent = nullptr);
199 ~QDBusConnectionPrivate();
200
201 void createBusService();
202 void setPeer(DBusConnection *connection, const QDBusErrorInternal &error);
203 void setConnection(DBusConnection *connection, const QDBusErrorInternal &error);
204 void setServer(QDBusServer *object, DBusServer *server, const QDBusErrorInternal &error);
205 void closeConnection();
206
207 QString getNameOwner(const QString &service);
208
209 bool shouldWatchService(const QString &service);
210 void watchService(const QString &service, QDBusServiceWatcher::WatchMode mode,
211 QObject *obj, const char *member);
212 void unwatchService(const QString &service, QDBusServiceWatcher::WatchMode mode,
213 QObject *obj, const char *member);
214
215 bool send(const QDBusMessage &message);
216 QDBusMessage sendWithReply(const QDBusMessage &message, int mode, int timeout = -1);
217 QDBusMessage sendWithReplyLocal(const QDBusMessage &message);
218 QDBusPendingCallPrivate *sendWithReplyAsync(const QDBusMessage &message, QObject *receiver,
219 const char *returnMethod, const char *errorMethod,int timeout = -1);
220
221 bool connectSignal(const QString &service, const QString &path, const QString& interface,
222 const QString &name, const QStringList &argumentMatch, const QString &signature,
223 QObject *receiver, const char *slot);
224 bool disconnectSignal(const QString &service, const QString &path, const QString& interface,
225 const QString &name, const QStringList &argumentMatch, const QString &signature,
226 QObject *receiver, const char *slot);
227 bool connectSignal(const QString &service, const QString &path, const QString& interface,
228 const QString &name, const ArgMatchRules &argumentMatch, const QString &signature,
229 QObject *receiver, const char *slot);
230 bool disconnectSignal(const QString &service, const QString &path, const QString& interface,
231 const QString &name, const ArgMatchRules &argumentMatch, const QString &signature,
232 QObject *receiver, const char *slot);
233 void registerObject(const ObjectTreeNode *node);
234 void unregisterObject(const QString &path, QDBusConnection::UnregisterMode mode);
235 void connectRelay(const QString &service,
236 const QString &path, const QString &interface,
237 QDBusAbstractInterface *receiver, const QMetaMethod &signal);
238 void disconnectRelay(const QString &service,
239 const QString &path, const QString &interface,
240 QDBusAbstractInterface *receiver, const QMetaMethod &signal);
241 void registerService(const QString &serviceName);
242 void unregisterService(const QString &serviceName);
243
244 bool handleMessage(const QDBusMessage &msg);
245
246 QDBusMetaObject *findMetaObject(const QString &service, const QString &path,
247 const QString &interface, QDBusError &error);
248
249 void postEventToThread(int action, QObject *target, QEvent *event);
250
251private:
252 void checkThread();
253 bool handleError(const QDBusErrorInternal &error);
254
255 void handleSignal(const QString &key, const QDBusMessage &msg);
256 void handleSignal(const QDBusMessage &msg);
257 void handleObjectCall(const QDBusMessage &message);
258
259 void activateSignal(const SignalHook& hook, const QDBusMessage &msg);
260 void activateObject(ObjectTreeNode &node, const QDBusMessage &msg, int pathStartPos);
261 bool activateInternalFilters(const ObjectTreeNode &node, const QDBusMessage &msg);
262 bool activateCall(QObject *object, int flags, const QDBusMessage &msg);
263
264 void sendInternal(QDBusPendingCallPrivate *pcall, void *msg, int timeout);
265 void sendError(const QDBusMessage &msg, QDBusError::ErrorType code);
266 void deliverCall(QObject *object, int flags, const QDBusMessage &msg,
267 const QList<QMetaType> &metaTypes, int slotIdx);
268
269 SignalHookHash::Iterator removeSignalHookNoLock(SignalHookHash::Iterator it);
270 void collectAllObjects(ObjectTreeNode &node, QSet<QObject *> &set);
271
272 bool isServiceRegisteredByThread(const QString &serviceName);
273
274 QString getNameOwnerNoCache(const QString &service);
275
276 void watchForDBusDisconnection();
277
278 void _q_newConnection(QDBusConnectionPrivate *newConnection);
279
280 void handleAuthentication();
281
282protected:
283 void timerEvent(QTimerEvent *e) override;
284
285public slots:
286 // public slots
287 void setDispatchEnabled(bool enable);
288 void doDispatch();
289 void socketRead(qintptr);
290 void socketWrite(qintptr);
291 void objectDestroyed(QObject *o);
292 void relaySignal(QObject *obj, const QMetaObject *, int signalId, const QVariantList &args);
293 bool addSignalHook(const QString &key, const SignalHook &hook);
294 bool removeSignalHook(const QString &key, const SignalHook &hook);
295
296private slots:
297 void serviceOwnerChangedNoLock(const QString &name, const QString &oldOwner, const QString &newOwner);
298 void registerServiceNoLock(const QString &serviceName);
299 void unregisterServiceNoLock(const QString &serviceName);
300 void handleDBusDisconnection();
301
302signals:
303 void dispatchStatusChanged();
304 void spyHooksFinished(const QDBusMessage &msg);
305 void messageNeedsSending(QDBusPendingCallPrivate *pcall, void *msg, int timeout = -1);
306 bool signalNeedsConnecting(const QString &key, const QDBusConnectionPrivate::SignalHook &hook);
307 bool signalNeedsDisconnecting(const QString &key, const QDBusConnectionPrivate::SignalHook &hook);
308 void serviceOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner);
309 void callWithCallbackFailed(const QDBusError &error, const QDBusMessage &message);
310 void newServerConnection(QDBusConnectionPrivate *newConnection);
311
312public:
313 QAtomicInt ref;
314 QAtomicInt capabilities;
315 QDBusConnection::ConnectionCapabilities connectionCapabilities() const
316 {
317 return (QDBusConnection::ConnectionCapabilities)capabilities.loadRelaxed();
318 }
319 QString name; // this connection's name
320 QString baseService; // this connection's base service
321 QStringList serverConnectionNames;
322
323 ConnectionMode mode;
324 union {
325 QDBusConnectionInterface *busService;
326 QDBusServer *serverObject;
327 };
328
329 union {
330 DBusConnection *connection;
331 DBusServer *server;
332 };
333 WatcherHash watchers;
334 TimeoutHash timeouts;
335 PendingMessageList pendingMessages;
336
337 // the master lock protects our own internal state
338 QReadWriteLock lock;
339 QDBusError lastError;
340
341 QStringList serviceNames;
342 WatchedServicesHash watchedServices;
343 SignalHookHash signalHooks;
344 MatchRefCountHash matchRefCounts;
345 ObjectTreeNode rootNode;
346 MetaObjectHash cachedMetaObjects;
347 PendingCallList pendingCalls;
348
349 bool anonymousAuthenticationAllowed;
350 bool dispatchEnabled; // protected by the dispatch lock, not the main lock
351 bool isAuthenticated;
352
353public:
354 // static methods
355 static int findSlot(QObject *obj, const QByteArray &normalizedName, QList<QMetaType> &params);
356 static bool prepareHook(QDBusConnectionPrivate::SignalHook &hook, QString &key,
357 const QString &service,
358 const QString &path, const QString &interface, const QString &name,
359 const ArgMatchRules &argMatch,
360 QObject *receiver, const char *signal, int minMIdx,
361 bool buildSignature);
362 static DBusHandlerResult messageFilter(DBusConnection *, DBusMessage *, void *);
363 static QDBusCallDeliveryEvent *prepareReply(QDBusConnectionPrivate *target, QObject *object,
364 int idx, const QList<QMetaType> &metaTypes,
365 const QDBusMessage &msg);
366 static void processFinishedCall(QDBusPendingCallPrivate *call);
367
368 static QDBusConnectionPrivate *d(const QDBusConnection& q) { return q.d; }
369 static QDBusConnection q(QDBusConnectionPrivate *connection) { return QDBusConnection(connection); }
370
371 friend class QDBusActivateObjectEvent;
372 friend class QDBusCallDeliveryEvent;
373 friend class QDBusServer;
374};
375
376// in qdbusmisc.cpp
377extern int qDBusParametersForMethod(const QMetaMethod &mm, QList<QMetaType> &metaTypes, QString &errorMsg);
378# endif // QT_BOOTSTRAPPED
379extern Q_DBUS_EXPORT int qDBusParametersForMethod(const QList<QByteArray> &parameters,
380 QList<QMetaType> &metaTypes, QString &errorMsg);
381extern Q_DBUS_EXPORT bool qDBusCheckAsyncTag(const char *tag);
382#ifndef QT_BOOTSTRAPPED
383extern bool qDBusInterfaceInObject(QObject *obj, const QString &interface_name);
384extern QString qDBusInterfaceFromMetaObject(const QMetaObject *mo);
385
386// in qdbusinternalfilters.cpp
387extern QString qDBusIntrospectObject(const QDBusConnectionPrivate::ObjectTreeNode &node, const QString &path);
388extern QDBusMessage qDBusPropertyGet(const QDBusConnectionPrivate::ObjectTreeNode &node,
389 const QDBusMessage &msg);
390extern QDBusMessage qDBusPropertySet(const QDBusConnectionPrivate::ObjectTreeNode &node,
391 const QDBusMessage &msg);
392extern QDBusMessage qDBusPropertyGetAll(const QDBusConnectionPrivate::ObjectTreeNode &node,
393 const QDBusMessage &msg);
394
395// can be replaced with a lambda in Qt 5.7
396class QDBusConnectionDispatchEnabler : public QObject
397{
398 Q_OBJECT
399 QDBusConnectionPrivate *con;
400public:
401 QDBusConnectionDispatchEnabler(QDBusConnectionPrivate *con) : con(con) {}
402
403public slots:
404 void execute()
405 {
406 // This call cannot race with something disabling dispatch only because dispatch is
407 // never re-disabled from Qt code on an in-use connection once it has been enabled.
408 QMetaObject::invokeMethod(con, "setDispatchEnabled", Qt::QueuedConnection, Q_ARG(bool, true));
409 if (!con->ref.deref())
410 con->deleteLater();
411 deleteLater();
412 }
413};
414
415#endif // QT_BOOTSTRAPPED
416
417QT_END_NAMESPACE
418
419#endif // QT_NO_DBUS
420#endif
421