Krita Source Code Documentation
Loading...
Searching...
No Matches
qtlocalpeer.cpp
Go to the documentation of this file.
1// Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
2// SPDX-License-Identifier: BSD-3-Clause
3
4
5#include "qtlocalpeer.h"
6#include <QCoreApplication>
7#include <QDataStream>
8#include <QRegularExpression>
9#include <QTime>
10
11#if defined(Q_OS_WIN)
12#include <QLibrary>
13#include <qt_windows.h>
14typedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);
15static PProcessIdToSessionId pProcessIdToSessionId = 0;
16#endif
17#if defined(Q_OS_UNIX)
18#include <sys/types.h>
19#include <time.h>
20#include <unistd.h>
21#endif
22
23namespace QtLP_Private {
24#include "qtlockedfile.cpp"
25#if defined(Q_OS_WIN)
26#include "qtlockedfile_win.cpp"
27#else
28#include "qtlockedfile_unix.cpp"
29#endif
30}
31
32const char* QtLocalPeer::ack = "ack";
33
34QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
35 : QObject(parent), id(appId)
36{
37 QString prefix = id;
38 if (id.isEmpty()) {
39 id = QCoreApplication::applicationFilePath();
40#if defined(Q_OS_WIN)
41 id = id.toLower();
42#endif
43 prefix = id.section(QLatin1Char('/'), -1);
44 }
45 prefix.remove(QRegularExpression("[^a-zA-Z]"));
46 prefix.truncate(6);
47
48 QByteArray idc = id.toUtf8();
49 quint16 idNum = qChecksum(idc.constData(), idc.size());
50 socketName = QLatin1String("qtsingleapp-") + prefix
51 + QLatin1Char('-') + QString::number(idNum, 16);
52
53#if defined(Q_OS_WIN)
54 if (!pProcessIdToSessionId) {
55 QLibrary lib("kernel32");
56 pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
57 }
58 if (pProcessIdToSessionId) {
59 DWORD sessionId = 0;
60 pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
61 socketName += QLatin1Char('-') + QString::number(sessionId, 16);
62 }
63#else
64 socketName += QLatin1Char('-') + QString::number(::getuid(), 16);
65#endif
66
67 server = new QLocalServer(this);
68 QString lockName = QDir(QDir::tempPath()).absolutePath()
69 + QLatin1Char('/') + socketName
70 + QLatin1String("-lockfile");
71 lockFile.setFileName(lockName);
72 lockFile.open(QIODevice::ReadWrite);
73
74 connect(this,
76 this,
78 Qt::QueuedConnection);
79}
80
81
82
84{
85 if (lockFile.isLocked())
86 return false;
87
89 return true;
90
91 bool res = server->listen(socketName);
92#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
93 // ### Workaround
94 if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
95 QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
96 res = server->listen(socketName);
97 }
98#endif
99 if (!res)
100 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
101 QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));
102 return false;
103}
104
105
106bool QtLocalPeer::sendMessage(const QString &message, int timeout)
107{
108 if (!isClient())
109 return false;
110
111 QLocalSocket socket;
112 bool connOk = false;
113 for(int i = 0; i < 2; i++) {
114 // Try twice, in case the other instance is just starting up
115 socket.connectToServer(socketName);
116 connOk = socket.waitForConnected(timeout/2);
117 if (connOk || i)
118 break;
119 int ms = 250;
120#if defined(Q_OS_WIN)
121 Sleep(DWORD(ms));
122#else
123 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
124 nanosleep(&ts, NULL);
125#endif
126 }
127 if (!connOk)
128 return false;
129
130 QByteArray uMsg(message.toUtf8());
131 QDataStream ds(&socket);
132 ds.writeBytes(uMsg.constData(), uMsg.size());
133 bool res = socket.waitForBytesWritten(timeout);
134 if (res) {
135 res &= socket.waitForReadyRead(timeout); // wait for ack
136 if (res)
137 res &= (socket.read(qstrlen(ack)) == ack);
138 }
139 return res;
140}
141
143{
144 if (!ready) {
145 ready = true;
146 for (const QString &queuedMessage : queuedMessages) {
147 Q_EMIT messageReceived(queuedMessage);
148 }
149 queuedMessages.clear();
150 }
151}
152
154{
155 QLocalSocket* socket = server->nextPendingConnection();
156 if (!socket)
157 return;
158
159 while (true) {
160 if (socket->state() == QLocalSocket::UnconnectedState) {
161 qWarning("QtLocalPeer: Peer disconnected");
162 delete socket;
163 return;
164 }
165 if (socket->bytesAvailable() >= qint64(sizeof(quint32)))
166 break;
167 socket->waitForReadyRead();
168 }
169
170 QDataStream ds(socket);
171 QByteArray uMsg;
172 quint32 remaining;
173 ds >> remaining;
174 uMsg.resize(remaining);
175 int got = 0;
176 char* uMsgBuf = uMsg.data();
177 do {
178 got = ds.readRawData(uMsgBuf, remaining);
179 remaining -= got;
180 uMsgBuf += got;
181 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
182 if (got < 0) {
183 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
184 delete socket;
185 return;
186 }
187 QString message(QString::fromUtf8(uMsg));
188 socket->write(ack, qstrlen(ack));
189 socket->waitForBytesWritten(1000);
190 socket->waitForDisconnected(1000); // make sure client reads ack
191 delete socket;
192 Q_EMIT sigMessageReceivedInternal(message);
193}
194
195void QtLocalPeer::slotHandleMessageInternal(const QString &message)
196{
197 if (ready) {
198 Q_EMIT messageReceived(message);
199 } else {
200 queuedMessages.append(message);
201 }
202}
bool open(OpenMode mode)
bool lock(LockMode mode, bool block=true)
QVector< QString > queuedMessages
Definition qtlocalpeer.h:44
QString socketName
Definition qtlocalpeer.h:35
void sigMessageReceivedInternal(const QString &message)
void messageReceived(const QString &message)
bool isClient()
QtLocalPeer(QObject *parent=0, const QString &appId=QString())
static const char * ack
Definition qtlocalpeer.h:43
QString id
Definition qtlocalpeer.h:34
bool sendMessage(const QString &message, int timeout)
void slotHandleMessageInternal(const QString &message)
QtLP_Private::QtLockedFile lockFile
Definition qtlocalpeer.h:37
QLocalServer * server
Definition qtlocalpeer.h:36
void receiveConnection()