strawberry-audio-player-win.../3rdparty/singleapplication/singlecoreapplication_p.cpp

527 lines
15 KiB
C++
Raw Normal View History

2019-01-11 01:04:13 +01:00
// The MIT License (MIT)
//
2020-10-05 21:31:03 +02:00
// Copyright (c) Itay Grudev 2015 - 2020
2019-01-11 01:04:13 +01:00
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// W A R N I N G !!!
// -----------------
//
// This is a modified version of SingleApplication,
// The original version is at:
2019-01-11 01:04:13 +01:00
//
// https://github.com/itay-grudev/SingleApplication
//
//
#include "config.h"
#include <QtGlobal>
2019-01-11 01:04:13 +01:00
#include <cstdlib>
#include <cstddef>
#ifdef Q_OS_UNIX
# include <unistd.h>
# include <sys/types.h>
# include <pwd.h>
#endif
2022-02-06 00:07:15 +01:00
#ifdef Q_OS_WIN
# ifndef NOMINMAX
# define NOMINMAX 1
# endif
# include <windows.h>
# include <lmcons.h>
#endif
2020-10-05 21:31:03 +02:00
#include <QObject>
#include <QThread>
2020-02-08 03:40:30 +01:00
#include <QIODevice>
#include <QSharedMemory>
#include <QByteArray>
#include <QDataStream>
#include <QCryptographicHash>
#include <QLocalServer>
#include <QLocalSocket>
2020-10-05 21:31:03 +02:00
#include <QElapsedTimer>
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
# include <QRandomGenerator>
#else
# include <QDateTime>
#endif
2019-01-11 01:04:13 +01:00
#include "singlecoreapplication.h"
#include "singlecoreapplication_p.h"
2020-10-05 21:31:03 +02:00
SingleCoreApplicationPrivate::SingleCoreApplicationPrivate(SingleCoreApplication *ptr)
: q_ptr(ptr),
memory_(nullptr),
socket_(nullptr),
server_(nullptr),
instanceNumber_(-1) {}
2019-01-11 01:04:13 +01:00
SingleCoreApplicationPrivate::~SingleCoreApplicationPrivate() {
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
if (socket_ != nullptr) {
socket_->close();
delete socket_;
socket_ = nullptr;
}
if (memory_ != nullptr) {
memory_->lock();
2022-02-06 00:07:15 +01:00
InstancesInfo *instance = static_cast<InstancesInfo*>(memory_->data());
2020-10-05 21:31:03 +02:00
if (server_ != nullptr) {
server_->close();
delete server_;
2022-02-06 00:07:15 +01:00
instance->primary = false;
instance->primaryPid = -1;
instance->primaryUser[0] = '\0';
instance->checksum = blockChecksum();
2020-10-05 21:31:03 +02:00
}
memory_->unlock();
delete memory_;
memory_ = nullptr;
}
}
QString SingleCoreApplicationPrivate::getUsername() {
#ifdef Q_OS_UNIX
QString username;
#if defined(HAVE_GETEUID) && defined(HAVE_GETPWUID)
struct passwd *pw = getpwuid(geteuid());
if (pw) {
username = QString::fromLocal8Bit(pw->pw_name);
}
2020-10-05 21:31:03 +02:00
#endif
if (username.isEmpty()) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
username = qEnvironmentVariable("USER");
#else
username = QString::fromLocal8Bit(qgetenv("USER"));
#endif
}
return username;
#endif
2020-10-05 21:31:03 +02:00
#ifdef Q_OS_WIN
wchar_t username[UNLEN + 1];
// Specifies size of the buffer on input
DWORD usernameLength = UNLEN + 1;
if (GetUserNameW(username, &usernameLength)) {
return QString::fromWCharArray(username);
}
2020-10-05 21:31:03 +02:00
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
return qEnvironmentVariable("USERNAME");
#else
return QString::fromLocal8Bit(qgetenv("USERNAME"));
#endif
#endif
2019-01-11 01:04:13 +01:00
}
void SingleCoreApplicationPrivate::genBlockServerName() {
2019-01-11 01:04:13 +01:00
QCryptographicHash appData(QCryptographicHash::Sha256);
appData.addData("SingleApplication");
appData.addData(SingleCoreApplication::app_t::applicationName().toUtf8());
appData.addData(SingleCoreApplication::app_t::organizationName().toUtf8());
appData.addData(SingleCoreApplication::app_t::organizationDomain().toUtf8());
2020-10-05 21:31:03 +02:00
if (!(options_ & SingleCoreApplication::Mode::ExcludeAppVersion)) {
appData.addData(SingleCoreApplication::app_t::applicationVersion().toUtf8());
}
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
if (!(options_ & SingleCoreApplication::Mode::ExcludeAppPath)) {
2022-02-06 00:07:15 +01:00
#if defined(Q_OS_UNIX)
const QByteArray appImagePath = qgetenv("APPIMAGE");
if (appImagePath.isEmpty()) {
appData.addData(SingleCoreApplication::app_t::applicationFilePath().toUtf8());
}
else {
appData.addData(appImagePath);
};
#elif defined(Q_OS_WIN)
appData.addData(SingleCoreApplication::app_t::applicationFilePath().toLower().toUtf8());
2019-01-11 01:04:13 +01:00
#else
appData.addData(SingleCoreApplication::app_t::applicationFilePath().toUtf8());
2019-01-11 01:04:13 +01:00
#endif
}
2019-01-11 01:04:13 +01:00
// User level block requires a user specific data in the hash
2020-10-05 21:31:03 +02:00
if (options_ & SingleCoreApplication::Mode::User) {
appData.addData(getUsername().toUtf8());
}
// Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with server naming requirements.
2020-10-05 21:31:03 +02:00
blockServerName_ = appData.result().toBase64().replace("/", "_");
2019-01-11 01:04:13 +01:00
}
2021-08-25 02:29:05 +02:00
void SingleCoreApplicationPrivate::initializeMemoryBlock() const {
2022-02-06 00:07:15 +01:00
InstancesInfo *instance = static_cast<InstancesInfo*>(memory_->data());
instance->primary = false;
instance->secondary = 0;
instance->primaryPid = -1;
instance->primaryUser[0] = '\0';
instance->checksum = blockChecksum();
2020-10-05 21:31:03 +02:00
2019-01-11 01:04:13 +01:00
}
void SingleCoreApplicationPrivate::startPrimary() {
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
// Reset the number of connections
2022-02-06 00:07:15 +01:00
InstancesInfo *instance = static_cast<InstancesInfo*>(memory_->data());
2020-10-05 21:31:03 +02:00
2022-02-06 00:07:15 +01:00
instance->primary = true;
instance->primaryPid = QCoreApplication::applicationPid();
qstrncpy(instance->primaryUser, getUsername().toUtf8().data(), sizeof(instance->primaryUser));
instance->checksum = blockChecksum();
2020-10-05 21:31:03 +02:00
instanceNumber_ = 0;
// Successful creation means that no main process exists
// So we start a QLocalServer to listen for connections
2020-10-05 21:31:03 +02:00
QLocalServer::removeServer(blockServerName_);
server_ = new QLocalServer();
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
// Restrict access to the socket according to the SingleCoreApplication::Mode::User flag on User level or no restrictions
if (options_ & SingleCoreApplication::Mode::User) {
server_->setSocketOptions(QLocalServer::UserAccessOption);
}
else {
2020-10-05 21:31:03 +02:00
server_->setSocketOptions(QLocalServer::WorldAccessOption);
}
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
server_->listen(blockServerName_);
QObject::connect(server_, &QLocalServer::newConnection, this, &SingleCoreApplicationPrivate::slotConnectionEstablished);
2020-10-05 21:31:03 +02:00
}
2020-10-05 21:31:03 +02:00
void SingleCoreApplicationPrivate::startSecondary() {
2022-02-06 00:07:15 +01:00
InstancesInfo *instance = static_cast<InstancesInfo*>(memory_->data());
2020-10-05 21:31:03 +02:00
2022-02-06 00:07:15 +01:00
instance->secondary += 1;
instance->checksum = blockChecksum();
instanceNumber_ = instance->secondary;
2019-01-11 01:04:13 +01:00
}
2021-03-21 18:53:02 +01:00
bool SingleCoreApplicationPrivate::connectToPrimary(const int timeout, const ConnectionType connectionType) {
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
QElapsedTimer time;
time.start();
2019-01-11 01:04:13 +01:00
// Connect to the Local Server of the Primary Instance if not already connected.
2020-10-05 21:31:03 +02:00
if (socket_ == nullptr) {
socket_ = new QLocalSocket();
}
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
if (socket_->state() == QLocalSocket::ConnectedState) return true;
2020-10-05 21:31:03 +02:00
if (socket_->state() != QLocalSocket::ConnectedState) {
forever {
randomSleep();
2021-08-23 21:21:08 +02:00
if (socket_->state() != QLocalSocket::ConnectingState) {
2020-10-05 21:31:03 +02:00
socket_->connectToServer(blockServerName_);
2021-08-23 21:21:08 +02:00
}
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
if (socket_->state() == QLocalSocket::ConnectingState) {
2021-03-21 18:53:02 +01:00
socket_->waitForConnected(static_cast<int>(timeout - time.elapsed()));
2020-10-05 21:31:03 +02:00
}
// If connected break out of the loop
if (socket_->state() == QLocalSocket::ConnectedState) break;
// If elapsed time since start is longer than the method timeout return
if (time.elapsed() >= timeout) return false;
}
}
// Initialisation message according to the SingleCoreApplication protocol
2020-10-05 21:31:03 +02:00
QByteArray initMsg;
QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
writeStream.setVersion(QDataStream::Qt_5_8);
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
writeStream << blockServerName_.toLatin1();
writeStream << static_cast<quint8>(connectionType);
writeStream << instanceNumber_;
2019-01-11 01:04:13 +01:00
2020-09-04 21:54:59 +02:00
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
2022-02-06 00:07:15 +01:00
quint16 checksum = qChecksum(QByteArray(initMsg, static_cast<quint32>(initMsg.length())));
2020-09-04 21:54:59 +02:00
#else
2020-10-05 21:31:03 +02:00
quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
2020-09-04 21:54:59 +02:00
#endif
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
writeStream << checksum;
2019-01-11 01:04:13 +01:00
2022-02-06 00:07:15 +01:00
return writeConfirmedMessage(static_cast<int>(timeout - time.elapsed()), initMsg);
}
void SingleCoreApplicationPrivate::writeAck(QLocalSocket *sock) {
sock->putChar('\n');
}
2022-02-06 04:18:40 +01:00
bool SingleCoreApplicationPrivate::writeConfirmedMessage(const int timeout, const QByteArray &msg) const {
2022-02-06 00:07:15 +01:00
QElapsedTimer time;
time.start();
// Frame 1: The header indicates the message length that follows
2020-10-05 21:31:03 +02:00
QByteArray header;
QDataStream headerStream(&header, QIODevice::WriteOnly);
headerStream.setVersion(QDataStream::Qt_5_8);
2022-02-06 00:07:15 +01:00
headerStream << static_cast<quint64>(msg.length());
if (!writeConfirmedFrame(static_cast<int>(timeout - time.elapsed()), header)) {
return false;
}
// Frame 2: The message
return writeConfirmedFrame(static_cast<int>(timeout - time.elapsed()), msg);
}
2020-02-29 21:50:10 +01:00
2022-02-06 04:18:40 +01:00
bool SingleCoreApplicationPrivate::writeConfirmedFrame(const int timeout, const QByteArray &msg) const {
2022-02-06 00:07:15 +01:00
socket_->write(msg);
2020-10-05 21:31:03 +02:00
socket_->flush();
2022-02-06 00:07:15 +01:00
bool result = socket_->waitForReadyRead(timeout);
if (result) {
socket_->read(1);
return true;
}
return false;
2019-01-11 01:04:13 +01:00
}
2021-06-22 13:45:29 +02:00
quint16 SingleCoreApplicationPrivate::blockChecksum() const {
2020-09-04 21:54:59 +02:00
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
2020-10-05 21:31:03 +02:00
quint16 checksum = qChecksum(QByteArray(static_cast<const char*>(memory_->constData()), offsetof(InstancesInfo, checksum)));
2020-09-04 21:54:59 +02:00
#else
2020-10-05 21:31:03 +02:00
quint16 checksum = qChecksum(static_cast<const char*>(memory_->constData()), offsetof(InstancesInfo, checksum));
2020-09-04 21:54:59 +02:00
#endif
return checksum;
2020-10-05 21:31:03 +02:00
2019-01-11 01:04:13 +01:00
}
2021-06-22 13:45:29 +02:00
qint64 SingleCoreApplicationPrivate::primaryPid() const {
2020-10-05 21:31:03 +02:00
memory_->lock();
2022-02-06 00:07:15 +01:00
InstancesInfo *instance = static_cast<InstancesInfo*>(memory_->data());
qint64 pid = instance->primaryPid;
2020-10-05 21:31:03 +02:00
memory_->unlock();
2019-01-11 01:04:13 +01:00
return pid;
2020-10-05 21:31:03 +02:00
}
2021-06-22 13:45:29 +02:00
QString SingleCoreApplicationPrivate::primaryUser() const {
2020-10-05 21:31:03 +02:00
memory_->lock();
2022-02-06 00:07:15 +01:00
InstancesInfo *instance = static_cast<InstancesInfo*>(memory_->data());
QByteArray username = instance->primaryUser;
2020-10-05 21:31:03 +02:00
memory_->unlock();
return QString::fromUtf8(username);
2019-01-11 01:04:13 +01:00
}
/**
* @brief Executed when a connection has been made to the LocalServer
*/
void SingleCoreApplicationPrivate::slotConnectionEstablished() {
2020-10-05 21:31:03 +02:00
QLocalSocket *nextConnSocket = server_->nextPendingConnection();
connectionMap_.insert(nextConnSocket, ConnectionInfo());
2021-03-21 04:36:54 +01:00
QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose, this, [nextConnSocket, this]() {
2022-02-06 00:07:15 +01:00
const ConnectionInfo &info = connectionMap_[nextConnSocket];
2021-03-21 04:36:54 +01:00
slotClientConnectionClosed(nextConnSocket, info.instanceId);
2020-10-05 21:31:03 +02:00
});
2022-02-06 00:07:15 +01:00
QObject::connect(nextConnSocket, &QLocalSocket::disconnected, nextConnSocket, &QLocalSocket::deleteLater);
QObject::connect(nextConnSocket, &QLocalSocket::destroyed, this, [nextConnSocket, this]() {
2020-10-05 21:31:03 +02:00
connectionMap_.remove(nextConnSocket);
});
2021-03-21 04:36:54 +01:00
QObject::connect(nextConnSocket, &QLocalSocket::readyRead, this, [nextConnSocket, this]() {
2022-02-06 00:07:15 +01:00
const ConnectionInfo &info = connectionMap_[nextConnSocket];
2020-10-05 21:31:03 +02:00
switch (info.stage) {
2022-02-06 00:07:15 +01:00
case StageInitHeader:
readMessageHeader(nextConnSocket, StageInitBody);
2020-10-05 21:31:03 +02:00
break;
2022-02-06 00:07:15 +01:00
case StageInitBody:
2020-10-05 21:31:03 +02:00
readInitMessageBody(nextConnSocket);
break;
2022-02-06 00:07:15 +01:00
case StageConnectedHeader:
readMessageHeader(nextConnSocket, StageConnectedBody);
break;
case StageConnectedBody:
this->slotDataAvailable(nextConnSocket, info.instanceId);
2020-10-05 21:31:03 +02:00
break;
default:
break;
};
});
}
2022-02-06 00:07:15 +01:00
void SingleCoreApplicationPrivate::readMessageHeader(QLocalSocket *sock, SingleCoreApplicationPrivate::ConnectionStage nextStage) {
2020-10-05 21:31:03 +02:00
if (!connectionMap_.contains(sock)) {
return;
}
2020-06-15 17:59:02 +02:00
if (sock->bytesAvailable() < static_cast<qint64>(sizeof(quint64))) {
return;
}
QDataStream headerStream(sock);
2020-10-05 21:31:03 +02:00
headerStream.setVersion(QDataStream::Qt_5_8);
2019-01-11 01:04:13 +01:00
// Read the header to know the message length
quint64 msgLen = 0;
headerStream >> msgLen;
2020-10-05 21:31:03 +02:00
ConnectionInfo &info = connectionMap_[sock];
2022-02-06 00:07:15 +01:00
info.stage = nextStage;
info.msgLen = msgLen;
2022-02-06 00:07:15 +01:00
writeAck(sock);
2020-10-05 21:31:03 +02:00
2019-01-11 01:04:13 +01:00
}
2022-02-06 00:07:15 +01:00
bool SingleCoreApplicationPrivate::isFrameComplete(QLocalSocket *sock) {
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
if (!connectionMap_.contains(sock)) {
2022-02-06 00:07:15 +01:00
return false;
}
2020-10-05 21:31:03 +02:00
ConnectionInfo &info = connectionMap_[sock];
2022-02-06 04:18:59 +01:00
return (sock->bytesAvailable() >= static_cast<qint64>(info.msgLen));
2022-02-06 00:07:15 +01:00
}
void SingleCoreApplicationPrivate::readInitMessageBody(QLocalSocket *sock) {
Q_Q(SingleCoreApplication);
if (!isFrameComplete(sock)) {
return;
}
2019-01-11 01:04:13 +01:00
// Read the message body
2022-02-06 00:07:15 +01:00
QByteArray msgBytes = sock->readAll();
QDataStream readStream(msgBytes);
2020-10-05 21:31:03 +02:00
readStream.setVersion(QDataStream::Qt_5_8);
2019-01-11 01:04:13 +01:00
// server name
QByteArray latin1Name;
readStream >> latin1Name;
2019-01-11 01:04:13 +01:00
// connection type
ConnectionType connectionType = InvalidConnection;
quint8 connTypeVal = InvalidConnection;
readStream >> connTypeVal;
2020-09-04 21:54:59 +02:00
connectionType = static_cast<ConnectionType>(connTypeVal);
2019-01-11 01:04:13 +01:00
// instance id
quint32 instanceId = 0;
readStream >> instanceId;
2019-01-11 01:04:13 +01:00
// checksum
quint16 msgChecksum = 0;
readStream >> msgChecksum;
2019-01-11 01:04:13 +01:00
2020-09-04 21:54:59 +02:00
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
2020-10-05 21:31:03 +02:00
const quint16 actualChecksum = qChecksum(QByteArray(msgBytes, static_cast<quint32>(msgBytes.length() - sizeof(quint16))));
2020-09-04 21:54:59 +02:00
#else
const quint16 actualChecksum = qChecksum(msgBytes.constData(), static_cast<quint32>(msgBytes.length() - sizeof(quint16)));
2020-09-04 21:54:59 +02:00
#endif
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
bool isValid = readStream.status() == QDataStream::Ok && QLatin1String(latin1Name) == blockServerName_ && msgChecksum == actualChecksum;
2019-01-11 01:04:13 +01:00
if (!isValid) {
sock->close();
return;
}
2019-01-11 01:04:13 +01:00
2022-02-06 00:07:15 +01:00
ConnectionInfo &info = connectionMap_[sock];
info.instanceId = instanceId;
2022-02-06 00:07:15 +01:00
info.stage = StageConnectedHeader;
2019-01-11 01:04:13 +01:00
2020-10-05 21:31:03 +02:00
if (connectionType == NewInstance || (connectionType == SecondaryInstance && options_ & SingleCoreApplication::Mode::SecondaryNotification)) {
2022-02-06 00:07:15 +01:00
emit q->instanceStarted();
}
2022-02-06 00:07:15 +01:00
writeAck(sock);
2020-10-05 21:31:03 +02:00
2019-01-11 01:04:13 +01:00
}
void SingleCoreApplicationPrivate::slotDataAvailable(QLocalSocket *dataSocket, const quint32 instanceId) {
Q_Q(SingleCoreApplication);
2022-02-06 00:07:15 +01:00
if (!isFrameComplete(dataSocket)) {
return;
}
const QByteArray message = dataSocket->readAll();
writeAck(dataSocket);
ConnectionInfo &info = connectionMap_[dataSocket];
info.stage = StageConnectedHeader;
emit q->receivedMessage(instanceId, message);
2020-10-05 21:31:03 +02:00
2019-01-11 01:04:13 +01:00
}
void SingleCoreApplicationPrivate::slotClientConnectionClosed(QLocalSocket *closedSocket, const quint32 instanceId) {
2020-10-05 21:31:03 +02:00
if (closedSocket->bytesAvailable() > 0) {
2021-03-21 04:36:54 +01:00
slotDataAvailable(closedSocket, instanceId);
2020-10-05 21:31:03 +02:00
}
}
void SingleCoreApplicationPrivate::randomSleep() {
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
2021-06-20 23:49:04 +02:00
QThread::msleep(QRandomGenerator::global()->bounded(8U, 18U));
2020-10-05 21:31:03 +02:00
#else
qsrand(QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max());
2022-02-06 00:07:15 +01:00
QThread::msleep(qrand() % 11 + 8);
2020-10-05 21:31:03 +02:00
#endif
2019-01-11 01:04:13 +01:00
}