swift
Loading...
Searching...
No Matches
dbusserver.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2014 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "misc/dbusserver.h"
5
6#include <QDBusServer>
7#include <QMetaClassInfo>
8#include <QMetaObject>
9#include <QStringList>
10#include <QtGlobal>
11
12#include "misc/logmessage.h"
14#include "misc/statusmessage.h"
15
16using namespace swift::misc::network;
17
18namespace swift::misc
19{
21 {
22 // Application Options:
23 // -h, –host=HOSTNAME Hostname or IP of the remote host
24 // -p, –port-ssh=PORT-SSH SSH port on the remote host
25 // -u, –username=USERNAME SSH username on the remote host
26 // -w, –password=PASSWORD SSH password on the remote host
27 // -m, –method=DBUS_TRANSPORT_METHOD The D-Bus transport method to use (TCP, UNIX, abstract-UNIX)
28 // -b, –bind=HOSTNAME The bind-address to listen for D-Bus client connections on
29 // -d, –bus-address=BUS_ADDRESS The DBus session bus address of the remote D-Bus daemon
30 // -t, –port-tcp=PORT-TCP The TCP port to listen for DBus client connections on
31 // -v, –verbose=VERBOSE Set verbosity level (3, 2, 1, 0, -1)=(packet,protocol,functions,important,none)
32
33 static const QString desc("Mode: %1 Address: '%2' Service: '%3'");
34 m_serverMode = CDBusServer::modeOfAddress(address);
35 this->setObjectName(
36 desc.arg(CDBusServer::modeToString(m_serverMode), address, service.isEmpty() ? "-" : service));
37 switch (m_serverMode)
38 {
39 case SERVERMODE_SESSIONBUS:
40 {
42 connection.unregisterService(service); // allow reconnecting by removing still registered service
43 if (!connection.isConnected() || !connection.registerService(service))
44 {
45 // registration fails can either mean something wrong with DBus or service already exists
46 CLogMessage(this).warning(u"DBus registration: %1") << connection.lastError().message();
47 CLogMessage(this).warning(u"Cannot register DBus service, check server running: dbus-daemon.exe "
48 u"--session --address=tcp:host=192.168.0.133,port=45000");
49 }
50 }
51 break;
52 case SERVERMODE_SYSTEMBUS:
53 {
55 connection.unregisterService(service); // allow reconnecting by removing still registered service
56 if (!connection.isConnected() || !connection.registerService(service))
57 {
58 // registration fails can either mean something wrong with DBus or service already exists
59 CLogMessage(this).warning(u"DBus registration: %1") << connection.lastError().message();
60 CLogMessage(this).warning(u"Cannot register DBus service, check server running: dbus-daemon.exe "
61 u"--system --address=tcp:host=192.168.0.133,port=45000");
62 }
63 }
64 break;
65 case SERVERMODE_P2P:
66 default:
67 {
68 QString dbusAddress = isQtDBusAddress(address) ? address : "tcp:host=127.0.0.1,port=45000";
69 dbusAddress = dbusAddress.toLower().trimmed().replace(' ', "");
70 if (!dbusAddress.contains("bind="))
71 {
72 dbusAddress = dbusAddress.append(",bind=*");
73 } // bind to all network interfaces
74
75 m_busServer.reset(new QDBusServer(dbusAddress, this));
76 m_busServer->setObjectName("QDBusServer: " + this->objectName());
77 m_busServer->setAnonymousAuthenticationAllowed(true);
78
79 // Note: P2P has no service name
80 if (m_busServer->isConnected())
81 {
82 CLogMessage(this).info(u"DBus P2P Server listening on address: '%1'") << m_busServer->address();
83 }
84 else
85 {
86 CLogMessage(this).warning(u"DBus P2P connection failed: %1") << lastQDBusServerError().message();
87 }
88 connect(m_busServer.data(), &QDBusServer::newConnection, this,
89 &CDBusServer::registerObjectsWithP2PConnection);
90 }
91 break;
92 }
93 }
94
100
102 {
103 static const QString sn = SWIFT_SERVICENAME;
104 return sn;
105 }
106
108 {
109 static const QString empty;
110 return CDBusServer::isP2PConnection(connection) ? empty : CDBusServer::coreServiceName();
111 }
112
114 {
115 static const QStringList cats({ CLogCategories::dbus() });
116 return cats;
117 }
118
119 bool CDBusServer::isP2PAddress(const QString &address) { return modeOfAddress(address) == SERVERMODE_P2P; }
120
122 {
124 {
125 return false;
126 }
127 return connection.name().contains(p2pConnectionName());
128 }
129
130 bool CDBusServer::dBusAddressToHostAndPort(const QString &address, QString &host, int &port)
131 {
132 const QString canonicalAddress = address.trimmed().toLower().replace(' ', "");
133 if (canonicalAddress.contains("host=") || canonicalAddress.contains("port="))
134 {
135 // "tcp:host=foo.com,port=123"
136 const QStringList parts(canonicalAddress.split(','));
137 for (const QString &part : parts)
138 {
139 // "host=" or "tcp:host="
140 if (part.contains("host=", Qt::CaseInsensitive))
141 {
142 const QString h = part.mid(part.lastIndexOf("=") + 1).trimmed();
143 host = h;
144 }
145 else if (part.contains("port=", Qt::CaseInsensitive))
146 {
147 const QString p = part.mid(part.lastIndexOf("=") + 1).trimmed();
148 bool ok {};
149 port = p.toInt(&ok);
150 if (!ok)
151 {
152 port = -1;
153 }
154 }
155 }
156 if (port < 0)
157 {
158 port = 45000;
159 }
160 if (host.isEmpty())
161 {
162 host = "127.0.0.1";
163 }
164 return true;
165 }
166 else
167 {
168 host = "";
169 port = -1;
170 return false;
171 }
172 }
173
174 bool CDBusServer::dBusAddressToHostAndPort(const QString &dbusAddress, QString &o_host, QString &o_port)
175 {
176 int port {};
177 const bool s = dBusAddressToHostAndPort(dbusAddress, o_host, port);
178 o_port = QString::number(port);
179 return s;
180 }
181
183 {
184 return connection.name() == QDBusConnection::sessionBus().name() ||
185 connection.name() == QDBusConnection::systemBus().name();
186 }
187
189 {
190 return address.startsWith("tcp:") || address.startsWith("unix:");
191 }
192
194 {
195 return address == sessionBusAddress() || address == systemBusAddress();
196 }
197
198 QString CDBusServer::getDBusInterfaceFromClassInfo(QObject *object)
199 {
200 if (!object)
201 {
202 return {};
203 }
204 const QMetaObject *mo = object->metaObject();
205 for (int i = 0; i < mo->classInfoCount(); i++)
206 {
207 const QMetaClassInfo ci = mo->classInfo(i);
208 const QString name = QString(ci.name()).toLower();
209 if (name == "d-bus interface")
210 {
211 return { ci.value() };
212 }
213 }
214 return {};
215 }
216
217 QDBusConnection::RegisterOptions CDBusServer::registerOptions()
218 {
220 }
221
222 bool CDBusServer::registerObjectsWithP2PConnection(QDBusConnection connection)
223 {
224 Q_ASSERT(!m_objects.isEmpty());
225 m_connections.insert(connection.name(), connection);
226 CLogMessage(this).info(u"New Connection from: '%1'") << connection.name();
227 bool success = true;
228 for (auto i = m_objects.cbegin(); i != m_objects.cend(); ++i)
229 {
230 const QString key(i.key());
231 const bool ok = connection.registerObject(key, i.value(), registerOptions());
232 if (ok)
233 {
234 CLogMessage(this).info(u"Adding '%1' to the new connection '%2'")
235 << key << getDBusInterfaceFromClassInfo(i.value());
236 }
237 else
238 {
239 CLogMessage(this).info(u"Adding '%1' failed, connection '%2', error '%3'")
240 << key << getDBusInterfaceFromClassInfo(i.value()) << connection.lastError().message();
241 success = false;
242 }
243 }
244 return success;
245 }
246
247 void CDBusServer::addObject(const QString &path, QObject *object)
248 {
249 if (!object)
250 {
251 return;
252 }
253 m_objects.insert(path, object); // will be registered when P2P connection is established
254
255 QObject::connect(object, &QObject::destroyed, this, [this, path] { m_objects.remove(path); });
256
257 switch (m_serverMode)
258 {
259 case SERVERMODE_SESSIONBUS:
260 {
262 if (connection.registerObject(path, object, registerOptions()))
263 {
264 CLogMessage(this).info(u"Adding '%1' '%2' to session DBus")
265 << path << getDBusInterfaceFromClassInfo(object);
266 }
267 else
268 {
269 CLogMessage(this).error(u"Error adding '%1' '%2' to session DBus: '%3'")
270 << path << getDBusInterfaceFromClassInfo(object) << connection.lastError().message();
271 }
272 }
273 break;
274 case SERVERMODE_SYSTEMBUS:
275 {
277 if (connection.registerObject(path, object, registerOptions()))
278 {
279 CLogMessage(this).info(u"Adding '%1' '%2' to system DBus")
280 << path << getDBusInterfaceFromClassInfo(object);
281 }
282 else
283 {
284 CLogMessage(this).error(u"Error adding '%1' '%2' to system DBus: '%3'")
285 << path << getDBusInterfaceFromClassInfo(object) << connection.lastError().message();
286 }
287 }
288 break;
289 case SERVERMODE_P2P:
290 {
291 for (QDBusConnection connection : std::as_const(m_connections))
292 {
293 if (connection.registerObject(path, object, registerOptions()))
294 {
295 CLogMessage(this).info(u"Adding '%1' '%2' to P2P DBus '%3'")
296 << path << getDBusInterfaceFromClassInfo(object) << connection.name();
297 }
298 else
299 {
300 CLogMessage(this).error(u"Error adding '%1' '%2' to P2P DBus '%3': '%4'")
301 << path << getDBusInterfaceFromClassInfo(object) << connection.name()
302 << connection.lastError().message();
303 }
304 }
305 }
306 break;
307 default: Q_ASSERT_X(false, Q_FUNC_INFO, "Wrong server mode");
308 }
309 }
310
312 {
313 if (!hasQDBusServer())
314 {
315 return {};
316 }
317 return m_busServer->lastError();
318 }
319
320 const QDBusServer *CDBusServer::qDBusServer() const { return m_busServer.data(); }
321
322 bool CDBusServer::hasQDBusServer() const { return !m_busServer.isNull(); }
323
325 {
326 for (const QString &path : makeKeysRange(std::as_const(m_objects)))
327 {
328 switch (m_serverMode)
329 {
330 case SERVERMODE_SESSIONBUS: QDBusConnection::sessionBus().unregisterObject(path); break;
331 case SERVERMODE_SYSTEMBUS: QDBusConnection::systemBus().unregisterObject(path); break;
332 case SERVERMODE_P2P:
333 for (QDBusConnection connection : std::as_const(m_connections))
334 {
335 connection.unregisterObject(path);
336 }
337 break;
338 }
339 }
340 m_objects.clear();
341 }
342
344 {
345 static const QDBusConnection defaultConnection("default");
346 return defaultConnection;
347 }
348
350 {
351 static const QString session("session");
352 return session;
353 }
354
356 {
357 static const QString system("system");
358 return system;
359 }
360
362 {
363 if (dBusAddress == sessionBusAddress())
364 {
365 if (name.isEmpty()) return QDBusConnection::sessionBus();
367 }
368 else if (dBusAddress == systemBusAddress())
369 {
370 if (name.isEmpty()) return QDBusConnection::systemBus();
372 }
373 else if (isP2PAddress(dBusAddress))
374 {
375 return QDBusConnection::connectToPeer(dBusAddress,
376 name.isEmpty() ? CDBusServer::p2pConnectionName() : name);
377 }
378 return QDBusConnection("invalid");
379 }
380
381 void CDBusServer::disconnectFromDBus(const QDBusConnection &connection, const QString &dBusAddress)
382 {
383 if (CDBusServer::isQtDefaultConnection(connection)) return; // do not touch the default connections
384 if (CDBusServer::isP2PAddress(dBusAddress))
385 {
387 }
388 else
389 {
391 }
392 }
393
395 {
396 QString h = host.trimmed().toLower().remove(' ');
397 if (h.isEmpty())
398 {
399 h = "127.0.0.1";
400 }
401
402 // check port
403 bool ok = false;
404 QString p = port.toLower().trimmed();
405 if (!p.isEmpty())
406 {
407 p.toShort(&ok); // cppcheck-suppress ignoredReturnValue
408 if (!ok)
409 {
410 p = ""; // was not a number
411 }
412 }
413
414 // can handle host and port separately or combined, e.g. "myhost:1234"
415 if (port.isEmpty())
416 {
417 if (h.startsWith("tcp:") && h.contains("host=") && h.contains("port="))
418 {
419 // looks we already got a full string
420 return h;
421 }
422
423 // 192.168.5.3:9300 style
424 if (h.contains(":"))
425 {
426 const QStringList parts = h.split(":");
427 h = parts.at(0).trimmed();
428 p = parts.at(1).trimmed();
429 }
430 else
431 {
432 p = "45000";
433 }
434 }
435
436 // todo: Replace assert with input validation
437 Q_ASSERT_X(CNetworkUtils::isValidIPv4Address(p), "CDBusServer::p2pAddress", "Wrong IP in String");
438 return QStringLiteral("tcp:host=%1,port=%2").arg(h, p);
439 }
440
442 {
443 static const QString n("p2pConnection");
444 return n;
445 }
446
448 {
449 const QString lc(address.toLower().trimmed());
450
451 if (lc.isEmpty())
452 {
453 return sessionBusAddress();
454 }
455 if (lc == sessionBusAddress() || lc == systemBusAddress())
456 {
457 return lc;
458 }
459
460 // some aliases
461 if (lc.startsWith("sys"))
462 {
463 return systemBusAddress();
464 }
465 if (lc.startsWith("ses"))
466 {
467 return sessionBusAddress();
468 }
469
470 // Qt / P2P
471 if (isQtDBusAddress(address))
472 {
473 return address;
474 }
475 return p2pAddress(address);
476 }
477
479 {
480 address = address.toLower();
481 if (address == systemBusAddress())
482 {
483 return SERVERMODE_SYSTEMBUS;
484 }
485 else if (address == sessionBusAddress())
486 {
487 return SERVERMODE_SESSIONBUS;
488 }
489 else
490 {
491 return SERVERMODE_P2P;
492 }
493 }
494
496 {
497 static const QString p2p = "P2P";
498 static const QString session = "session";
499 static const QString system = "system";
500
501 switch (mode)
502 {
503 case SERVERMODE_P2P: return p2p;
504 case SERVERMODE_SYSTEMBUS: return system;
505 case SERVERMODE_SESSIONBUS:
506 default: break;
507 }
508 return session;
509 }
510
511 bool CDBusServer::isDBusAvailable(const QString &address, int port, int timeoutMs)
512 {
513 QString unused;
514 return CNetworkUtils::canConnect(address, port, unused, timeoutMs);
515 }
516
517 bool CDBusServer::isDBusAvailable(const QString &address, int port, QString &message, int timeoutMs)
518 {
519 return CNetworkUtils::canConnect(address, port, message, timeoutMs);
520 }
521
522 bool CDBusServer::isDBusAvailable(const QString &dBusAddress, QString &message, int timeoutMs)
523 {
524 if (dBusAddress.isEmpty())
525 {
526 message = "No address.";
527 return false;
528 }
529 if (isP2PAddress(dBusAddress))
530 {
531 QString host;
532 int port = -1;
533 return CDBusServer::dBusAddressToHostAndPort(dBusAddress, host, port) ?
534 CDBusServer::isDBusAvailable(host, port, message, timeoutMs) :
535 false;
536 }
537 else
538 {
539 QDBusConnection connection = CDBusServer::connectToDBus(dBusAddress);
540 const bool isConnected = connection.isConnected();
541 message = connection.lastError().message();
542 CDBusServer::disconnectFromDBus(connection, dBusAddress);
543 return isConnected;
544 }
545 }
546
547 bool CDBusServer::isDBusAvailable(const QString &dbusAddress, int timeoutMs)
548 {
549 QString unused;
550 return CDBusServer::isDBusAvailable(dbusAddress, unused, timeoutMs);
551 }
552} // namespace swift::misc
static void disconnectFromDBus(const QDBusConnection &connection, const QString &dBusAddress)
Disconnect from Bus/Peer to peer.
static bool dBusAddressToHostAndPort(const QString &dbusAddress, QString &o_host, int &o_port)
Extract host and port from a DBus address.
static const QDBusConnection & defaultConnection()
Default connection.
void removeAllObjects()
Remove all objects added with addObject.
static const QString & systemBusAddress()
Address denoting a system bus server.
void addObject(const QString &name, QObject *object)
Add a QObject to be exposed via DBus.
static QDBusConnection connectToDBus(const QString &dbusAddress, const QString &name={})
Connect to DBus.
static bool isSessionOrSystemAddress(const QString &address)
True if address is session or system bus address.
bool hasQDBusServer() const
True if using P2P.
QDBusError lastQDBusServerError() const
Last error.
static const QString & modeToString(ServerMode mode)
Mode to string.
static ServerMode modeOfAddress(QString address)
Return the server mode of the given address.
static bool isDBusAvailable(const QString &host, int port, int timeoutMs=1500)
Is there a DBus server running at the given address?
static const QStringList & getLogCategories()
Log categories.
const QDBusServer * qDBusServer() const
DBus server (if using P2P).
static QString normalizeAddress(const QString &address)
Turn something like 127.0.0.1:45000 into "tcp:host=127.0.0.1,port=45000".
static const QString & sessionBusAddress()
Address denoting a session bus server.
static QString p2pAddress(const QString &host, const QString &port="")
Address denoting a P2P server at the given host and port.
static const QString & p2pConnectionName()
P2P connection name.
CDBusServer(const QString &address, QObject *parent=nullptr)
Construct a server for the core service.
Definition dbusserver.h:56
static bool isP2PConnection(const QDBusConnection &connection)
False if address is session or system bus connection.
static bool isQtDefaultConnection(const QDBusConnection &connection)
Is the given connection one of the default connections?
static bool isP2PAddress(const QString &address)
False if address is session or system bus address.
static const QString & coreServiceName()
Default service name.
static bool isQtDBusAddress(const QString &address)
True if a valid Qt DBus address, e.g. "unix:tmpdir=/tmp", "tcp:host=127.0.0.1,port=45000".
static const QString & dbus()
DBus related.
Class for emitting a log message.
Definition logmessage.h:27
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
static bool isValidIPv4Address(const QString &candidate)
Valid IPv4 address.
static bool canConnect(const QString &hostAddress, int port, QString &message, int timeoutMs=getTimeoutMs())
Can connect?
#define SWIFT_SERVICENAME
Service name of DBus service.
Definition dbusserver.h:23
Free functions in swift::misc.
auto makeKeysRange(const T &container)
Returns a const CRange for iterating over the keys of a Qt associative container.
Definition range.h:365
typedef RegisterOptions
QDBusConnection connectToBus(QDBusConnection::BusType type, const QString &name)
QDBusConnection connectToPeer(const QString &address, const QString &name)
void disconnectFromBus(const QString &name)
void disconnectFromPeer(const QString &name)
bool isConnected() const const
QDBusError lastError() const const
QString name() const const
bool registerObject(const QString &path, QObject *object, QDBusConnection::RegisterOptions options)
bool registerService(const QString &serviceName)
QDBusConnection sessionBus()
QDBusConnection systemBus()
void unregisterObject(const QString &path, QDBusConnection::UnregisterMode mode)
bool unregisterService(const QString &serviceName)
QString message() const const
void newConnection(const QDBusConnection &connection)
QList< T >::const_reference at(qsizetype i) const const
const char * name() const const
const char * value() const const
QMetaClassInfo classInfo(int index) const const
int classInfoCount() const const
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void destroyed(QObject *obj)
QObject * parent() const const
void setObjectName(QAnyStringView name)
QString & append(QChar ch)
QString arg(Args &&... args) const const
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
QString & insert(qsizetype position, QChar ch)
bool isEmpty() const const
QString mid(qsizetype position, qsizetype n) &&
QString number(double n, char format, int precision)
QString & remove(QChar ch, Qt::CaseSensitivity cs)
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
QStringList split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
int toInt(bool *ok, int base) const const
QString toLower() const const
short toShort(bool *ok, int base) const const
QString trimmed() const const
CaseInsensitive