QT6: Use the QByteArrayView overload.

This commit is contained in:
Simon De Backer
2020-10-01 21:45:52 +02:00
parent 3b71cb7dfe
commit 4f929ef3c9

View File

@@ -43,9 +43,9 @@
#include "singleapplication_p.h" #include "singleapplication_p.h"
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
#include <unistd.h> #include <unistd.h>
#include <sys/types.h> #include <sys/types.h>
#include <pwd.h> #include <pwd.h>
#endif #endif
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@@ -68,7 +68,7 @@ SingleApplicationPrivate::~SingleApplicationPrivate()
socket->close(); socket->close();
delete socket; delete socket;
} }
memory->lock(); memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data()); InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data());
if( server != nullptr ) { if( server != nullptr ) {
@@ -79,7 +79,7 @@ SingleApplicationPrivate::~SingleApplicationPrivate()
inst->checksum = blockChecksum(); inst->checksum = blockChecksum();
} }
memory->unlock(); memory->unlock();
delete memory; delete memory;
} }
@@ -90,11 +90,11 @@ void SingleApplicationPrivate::genBlockServerName()
appData.addData( SingleApplication::app_t::applicationName().toUtf8() ); appData.addData( SingleApplication::app_t::applicationName().toUtf8() );
appData.addData( SingleApplication::app_t::organizationName().toUtf8() ); appData.addData( SingleApplication::app_t::organizationName().toUtf8() );
appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() ); appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() );
if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) { if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) {
appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() ); appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() );
} }
if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) { if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() ); appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() );
@@ -102,7 +102,7 @@ void SingleApplicationPrivate::genBlockServerName()
appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() ); appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
#endif #endif
} }
// User level block requires a user specific data in the hash // User level block requires a user specific data in the hash
if( options & SingleApplication::Mode::User ) { if( options & SingleApplication::Mode::User ) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
@@ -128,7 +128,7 @@ void SingleApplicationPrivate::genBlockServerName()
appData.addData(username); appData.addData(username);
#endif #endif
} }
// Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with
// server naming requirements. // server naming requirements.
blockServerName = appData.result().toBase64().replace("/", "_"); blockServerName = appData.result().toBase64().replace("/", "_");
@@ -146,12 +146,12 @@ void SingleApplicationPrivate::initializeMemoryBlock()
void SingleApplicationPrivate::startPrimary() void SingleApplicationPrivate::startPrimary()
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
// Successful creation means that no main process exists // Successful creation means that no main process exists
// So we start a QLocalServer to listen for connections // So we start a QLocalServer to listen for connections
QLocalServer::removeServer( blockServerName ); QLocalServer::removeServer( blockServerName );
server = new QLocalServer(); server = new QLocalServer();
// Restrict access to the socket according to the // Restrict access to the socket according to the
// SingleApplication::Mode::User flag on User level or no restrictions // SingleApplication::Mode::User flag on User level or no restrictions
if( options & SingleApplication::Mode::User ) { if( options & SingleApplication::Mode::User ) {
@@ -159,7 +159,7 @@ void SingleApplicationPrivate::startPrimary()
} else { } else {
server->setSocketOptions( QLocalServer::WorldAccessOption ); server->setSocketOptions( QLocalServer::WorldAccessOption );
} }
server->listen( blockServerName ); server->listen( blockServerName );
QObject::connect( QObject::connect(
server, server,
@@ -167,14 +167,14 @@ void SingleApplicationPrivate::startPrimary()
this, this,
&SingleApplicationPrivate::slotConnectionEstablished &SingleApplicationPrivate::slotConnectionEstablished
); );
// Reset the number of connections // Reset the number of connections
InstancesInfo* inst = static_cast <InstancesInfo*>( memory->data() ); InstancesInfo* inst = static_cast <InstancesInfo*>( memory->data() );
inst->primary = true; inst->primary = true;
inst->primaryPid = q->applicationPid(); inst->primaryPid = q->applicationPid();
inst->checksum = blockChecksum(); inst->checksum = blockChecksum();
instanceNumber = 0; instanceNumber = 0;
} }
@@ -189,47 +189,62 @@ void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType conne
if( socket == nullptr ) { if( socket == nullptr ) {
socket = new QLocalSocket(); socket = new QLocalSocket();
} }
// If already connected - we are done; // If already connected - we are done;
if( socket->state() == QLocalSocket::ConnectedState ) if( socket->state() == QLocalSocket::ConnectedState )
return; return;
// If not connect // If not connect
if( socket->state() == QLocalSocket::UnconnectedState || if( socket->state() == QLocalSocket::UnconnectedState ||
socket->state() == QLocalSocket::ClosingState ) { socket->state() == QLocalSocket::ClosingState ) {
socket->connectToServer( blockServerName ); socket->connectToServer( blockServerName );
} }
// Wait for being connected // Wait for being connected
if( socket->state() == QLocalSocket::ConnectingState ) { if( socket->state() == QLocalSocket::ConnectingState ) {
socket->waitForConnected( msecs ); socket->waitForConnected( msecs );
} }
// Initialisation message according to the SingleApplication protocol // Initialisation message according to the SingleApplication protocol
if( socket->state() == QLocalSocket::ConnectedState ) { if( socket->state() == QLocalSocket::ConnectedState ) {
// Notify the parent that a new instance had been started; // Notify the parent that a new instance had been started;
QByteArray initMsg; QByteArray initMsg;
QDataStream writeStream(&initMsg, QIODevice::WriteOnly); QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
writeStream.setVersion(QDataStream::Qt_5_6); writeStream.setVersion(QDataStream::Qt_5_6);
#endif #endif
writeStream << blockServerName.toLatin1(); writeStream << blockServerName.toLatin1();
writeStream << static_cast<quint8>(connectionType); writeStream << static_cast<quint8>(connectionType);
writeStream << instanceNumber; writeStream << instanceNumber;
quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
quint16 checksum =
qChecksum(
initMsg.constData(),
static_cast<quint32>(initMsg.length()));
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
quint16 checksum =
qChecksum(
QByteArrayView(
initMsg.constData(),
static_cast<quint32>(initMsg.length())));
#endif
writeStream << checksum; writeStream << checksum;
// The header indicates the message length that follows // The header indicates the message length that follows
QByteArray header; QByteArray header;
QDataStream headerStream(&header, QIODevice::WriteOnly); QDataStream headerStream(&header, QIODevice::WriteOnly);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
headerStream.setVersion(QDataStream::Qt_5_6); headerStream.setVersion(QDataStream::Qt_5_6);
#endif #endif
headerStream << static_cast <quint64>( initMsg.length() ); headerStream << static_cast <quint64>( initMsg.length() );
socket->write( header ); socket->write( header );
socket->write( initMsg ); socket->write( initMsg );
socket->flush(); socket->flush();
@@ -239,21 +254,32 @@ void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType conne
quint16 SingleApplicationPrivate::blockChecksum() quint16 SingleApplicationPrivate::blockChecksum()
{ {
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
return qChecksum( return qChecksum(
static_cast <const char *>( memory->data() ), static_cast <const char *>( memory->data() ),
offsetof( InstancesInfo, checksum ) offsetof( InstancesInfo, checksum )
); );
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
return qChecksum(
QByteArrayView(
static_cast <const char *>( memory->data() ),
offsetof( InstancesInfo, checksum )));
#endif
} }
qint64 SingleApplicationPrivate::primaryPid() qint64 SingleApplicationPrivate::primaryPid()
{ {
qint64 pid; qint64 pid;
memory->lock(); memory->lock();
InstancesInfo* inst = static_cast<InstancesInfo*>( memory->data() ); InstancesInfo* inst = static_cast<InstancesInfo*>( memory->data() );
pid = inst->primaryPid; pid = inst->primaryPid;
memory->unlock(); memory->unlock();
return pid; return pid;
} }
@@ -264,21 +290,21 @@ void SingleApplicationPrivate::slotConnectionEstablished()
{ {
QLocalSocket *nextConnSocket = server->nextPendingConnection(); QLocalSocket *nextConnSocket = server->nextPendingConnection();
connectionMap.insert(nextConnSocket, ConnectionInfo()); connectionMap.insert(nextConnSocket, ConnectionInfo());
QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose, QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose,
[nextConnSocket, this]() { [nextConnSocket, this]() {
auto &info = connectionMap[nextConnSocket]; auto &info = connectionMap[nextConnSocket];
Q_EMIT this->slotClientConnectionClosed( nextConnSocket, info.instanceId ); Q_EMIT this->slotClientConnectionClosed( nextConnSocket, info.instanceId );
} }
); );
QObject::connect(nextConnSocket, &QLocalSocket::disconnected, QObject::connect(nextConnSocket, &QLocalSocket::disconnected,
[nextConnSocket, this](){ [nextConnSocket, this](){
connectionMap.remove(nextConnSocket); connectionMap.remove(nextConnSocket);
nextConnSocket->deleteLater(); nextConnSocket->deleteLater();
} }
); );
QObject::connect(nextConnSocket, &QLocalSocket::readyRead, QObject::connect(nextConnSocket, &QLocalSocket::readyRead,
[nextConnSocket, this]() { [nextConnSocket, this]() {
auto &info = connectionMap[nextConnSocket]; auto &info = connectionMap[nextConnSocket];
@@ -304,24 +330,24 @@ void SingleApplicationPrivate::readInitMessageHeader( QLocalSocket *sock )
if (!connectionMap.contains( sock )) { if (!connectionMap.contains( sock )) {
return; return;
} }
if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ) { if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ) {
return; return;
} }
QDataStream headerStream( sock ); QDataStream headerStream( sock );
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
headerStream.setVersion( QDataStream::Qt_5_6 ); headerStream.setVersion( QDataStream::Qt_5_6 );
#endif #endif
// Read the header to know the message length // Read the header to know the message length
quint64 msgLen = 0; quint64 msgLen = 0;
headerStream >> msgLen; headerStream >> msgLen;
ConnectionInfo &info = connectionMap[sock]; ConnectionInfo &info = connectionMap[sock];
info.stage = StageBody; info.stage = StageBody;
info.msgLen = msgLen; info.msgLen = msgLen;
if ( sock->bytesAvailable() >= (qint64) msgLen ) { if ( sock->bytesAvailable() >= (qint64) msgLen ) {
readInitMessageBody( sock ); readInitMessageBody( sock );
} }
@@ -330,63 +356,76 @@ void SingleApplicationPrivate::readInitMessageHeader( QLocalSocket *sock )
void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock ) void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock )
{ {
Q_Q(SingleApplication); Q_Q(SingleApplication);
if (!connectionMap.contains( sock )) { if (!connectionMap.contains( sock )) {
return; return;
} }
ConnectionInfo &info = connectionMap[sock]; ConnectionInfo &info = connectionMap[sock];
if( sock->bytesAvailable() < ( qint64 )info.msgLen ) { if( sock->bytesAvailable() < ( qint64 )info.msgLen ) {
return; return;
} }
// Read the message body // Read the message body
QByteArray msgBytes = sock->read(info.msgLen); QByteArray msgBytes = sock->read(info.msgLen);
QDataStream readStream(msgBytes); QDataStream readStream(msgBytes);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
readStream.setVersion( QDataStream::Qt_5_6 ); readStream.setVersion( QDataStream::Qt_5_6 );
#endif #endif
// server name // server name
QByteArray latin1Name; QByteArray latin1Name;
readStream >> latin1Name; readStream >> latin1Name;
// connection type // connection type
ConnectionType connectionType = InvalidConnection; ConnectionType connectionType = InvalidConnection;
quint8 connTypeVal = InvalidConnection; quint8 connTypeVal = InvalidConnection;
readStream >> connTypeVal; readStream >> connTypeVal;
connectionType = static_cast <ConnectionType>( connTypeVal ); connectionType = static_cast <ConnectionType>( connTypeVal );
// instance id // instance id
quint32 instanceId = 0; quint32 instanceId = 0;
readStream >> instanceId; readStream >> instanceId;
// checksum // checksum
quint16 msgChecksum = 0; quint16 msgChecksum = 0;
readStream >> msgChecksum; readStream >> msgChecksum;
const quint16 actualChecksum = qChecksum( msgBytes.constData(), static_cast<quint32>( msgBytes.length() - sizeof( quint16 ) ) ); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) // ### Qt 6: remove
const quint16 actualChecksum =
qChecksum(
msgBytes.constData(),
static_cast<quint32>( msgBytes.length() - sizeof( quint16 ) ) );
#else
#if TODO_LIST
#pragma message("@TODO remove code for QT 6 or later")
#endif
const quint16 actualChecksum =
qChecksum(
QByteArrayView(
msgBytes.constData(),
static_cast<quint32>(msgBytes.length() - sizeof(quint16))));
#endif
bool isValid = readStream.status() == QDataStream::Ok && bool isValid = readStream.status() == QDataStream::Ok &&
QLatin1String(latin1Name) == blockServerName && QLatin1String(latin1Name) == blockServerName &&
msgChecksum == actualChecksum; msgChecksum == actualChecksum;
if( !isValid ) { if( !isValid ) {
sock->close(); sock->close();
return; return;
} }
info.instanceId = instanceId; info.instanceId = instanceId;
info.stage = StageConnected; info.stage = StageConnected;
if( connectionType == NewInstance || if( connectionType == NewInstance ||
( connectionType == SecondaryInstance && ( connectionType == SecondaryInstance &&
options & SingleApplication::Mode::SecondaryNotification ) ) options & SingleApplication::Mode::SecondaryNotification ) )
{ {
Q_EMIT q->instanceStarted(); Q_EMIT q->instanceStarted();
} }
if (sock->bytesAvailable() > 0) { if (sock->bytesAvailable() > 0) {
Q_EMIT this->slotDataAvailable( sock, instanceId ); Q_EMIT this->slotDataAvailable( sock, instanceId );
} }