QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
singleapplication.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "singleapplication.h"
9#include "qtpasslogging.h"
10#include <QCryptographicHash>
11#include <QDebug>
12#include <QDir>
13#include <QFileInfo>
14#include <QLocalSocket>
15#include <QRandomGenerator>
16#include <QSharedPointer>
17#include <QStandardPaths>
18#include <QThread>
19#include <utility>
20
21#ifdef Q_OS_WIN
22#include <vector>
23#include <windows.h>
24#endif
25
27 int &argc, char *argv[], // NOLINT(modernize-avoid-c-arrays)
28 QString uniqueKey)
29 : QApplication(argc, argv), _uniqueKey(std::move(uniqueKey)),
31 // Stale only when its process is gone: a running instance holds the lock
32 // for as long as it runs, far beyond any age limit.
33 _lock.setStaleLockTime(0);
35}
36
37auto SingleApplication::privateKey(const QString &base) -> QString {
38#ifdef Q_OS_WIN
39 return base;
40#else
41 const QString dir =
42 QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
43 if (!dir.isEmpty()) {
44 QDir().mkpath(dir);
45 }
46 return privateKeyIn(base, dir);
47#endif
48}
49
50// Named after a hash of the base, so any login name makes a valid file name
51// and the path stays well under the 104 bytes macOS allows a socket path.
52auto SingleApplication::privateKeyIn(const QString &base, const QString &dir)
53 -> QString {
54 if (dir.isEmpty() || !QFileInfo(dir).isDir()) {
55 qCWarning(lcQtPass) << "SingleApplication: no private folder for the"
56 " socket; running without single instance.";
57 return base +
58 QStringLiteral("%1").arg(QRandomGenerator::system()->generate64(),
59 16, 16, QLatin1Char('0'));
60 }
61 const QByteArray hash =
62 QCryptographicHash::hash(base.toUtf8(), QCryptographicHash::Sha256)
63 .toHex()
64 .left(16);
65 return QDir(dir).filePath(QStringLiteral("qtpass-") +
66 QString::fromLatin1(hash));
67}
68
69#ifdef Q_OS_WIN
70namespace {
71
77auto tokenUser(HANDLE token) -> std::vector<BYTE> {
78 DWORD size = 0;
79 GetTokenInformation(token, TokenUser, nullptr, 0, &size);
80 if (size == 0) {
81 return {};
82 }
83 std::vector<BYTE> record(size);
84 if (!GetTokenInformation(token, TokenUser, record.data(), size, &size)) {
85 return {};
86 }
87 return record;
88}
89
95auto processUser(HANDLE process) -> std::vector<BYTE> {
96 HANDLE token = nullptr;
97 if (!OpenProcessToken(process, TOKEN_QUERY, &token)) {
98 return {};
99 }
100 std::vector<BYTE> record = tokenUser(token);
101 CloseHandle(token);
102 return record;
103}
104
105} // namespace
106#endif
107
108// Windows only: see the header. A server whose process or token this user
109// may not open is not this user's.
110auto SingleApplication::serverRunsAsThisUser(const QLocalSocket &socket)
111 -> bool {
112#ifdef Q_OS_WIN
113 // NOLINTNEXTLINE(performance-no-int-to-ptr): QLocalSocket gives the HANDLE
114 const auto pipe = reinterpret_cast<HANDLE>(socket.socketDescriptor());
115 ULONG pid = 0;
116 if (pipe == nullptr || pipe == INVALID_HANDLE_VALUE ||
117 !GetNamedPipeServerProcessId(pipe, &pid)) {
118 return false;
119 }
120 HANDLE server = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
121 if (server == nullptr) {
122 return false;
123 }
124 const std::vector<BYTE> theirs = processUser(server);
125 CloseHandle(server);
126 const std::vector<BYTE> ours = processUser(GetCurrentProcess());
127 if (theirs.empty() || ours.empty()) {
128 return false;
129 }
130 return EqualSid(
131 reinterpret_cast<const TOKEN_USER *>(theirs.data())->User.Sid,
132 reinterpret_cast<const TOKEN_USER *>(ours.data())->User.Sid) !=
133 FALSE;
134#else
135 Q_UNUSED(socket);
136 return true;
137#endif
138}
139
140auto SingleApplication::lockPathFor(const QString &key) -> QString {
141 if (QDir::isAbsolutePath(key)) {
142 return key + QStringLiteral(".lock");
143 }
144 QString name = key;
145 name.replace(QLatin1Char('/'), QLatin1Char('_'));
146 name.replace(QLatin1Char('\\'), QLatin1Char('_'));
147 return QDir(QDir::tempPath()).filePath(name + QStringLiteral(".lock"));
148}
149
150// public slots.
151
153 while (QLocalSocket *localSocket = localServer->nextPendingConnection()) {
154 auto buffer = QSharedPointer<QByteArray>::create();
155 connect(localSocket, &QLocalSocket::readyRead, this,
156 [localSocket, buffer]() {
157 buffer->append(localSocket->readAll());
158 if (buffer->size() > maxMessageBytes) {
159 // Not a command line any more; drop the peer and its data.
160 buffer->clear();
161 localSocket->abort();
162 }
163 });
164 connect(localSocket, &QLocalSocket::disconnected, this,
165 [this, localSocket, buffer]() {
166 // Nothing is left when the peer was dropped for sending too
167 // much, and Qt warns about a read from the socket abort()
168 // has closed.
169 if (localSocket->bytesAvailable() > 0) {
170 buffer->append(localSocket->readAll());
171 }
172 if (!buffer->isEmpty()) {
173 emit messageAvailable(QString::fromUtf8(buffer->constData()));
174 }
175 localSocket->deleteLater();
176 });
177 }
178}
179
180// public functions.
181auto SingleApplication::isRunning() -> bool { return _isRunning; }
182
183auto SingleApplication::sendMessage(const QString &message) -> bool {
184 if (!_isRunning) {
185 return false;
186 }
187 if (forwardMessage(message)) {
188 return true;
189 }
190 // The peer vanished between the probe in the constructor and now. Take its
191 // lock and its place, so the window main() opens next is the reachable
192 // instance; if it still holds the lock, it may be restarting its server.
193 _isRunning = false;
195 return false;
196}
197
198// private functions.
200 const bool leftOver = QFileInfo::exists(_lock.fileName());
201 if (_lock.tryLock(0)) {
202 if (leftOver) {
203 // A crash leaves the lock file behind; its process is gone.
204 qCDebug(lcQtPass) << "Stale single instance lock, taking over.";
205 }
207 return;
208 }
209 if (_lock.error() != QLockFile::LockFailedError) {
210 qCWarning(lcQtPass) << "SingleApplication: cannot take" << _lock.fileName()
211 << "; running without IPC.";
212 return;
213 }
214 qCDebug(lcQtPass) << "Single instance lock held, probing its server.";
215 waitForPeer();
216}
217
219 // A socket file left behind by a crashed instance would make listen() fail
220 // (address in use) and silently disable IPC for good, so clear it first:
221 // this instance holds the lock, so no live instance listens on it.
222 QLocalServer::removeServer(_uniqueKey);
223 localServer.reset(new QLocalServer(this));
224 localServer->setSocketOptions(QLocalServer::UserAccessOption);
225 connect(localServer.data(), &QLocalServer::newConnection, this,
227 if (!localServer->listen(_uniqueKey)) {
228 qCWarning(lcQtPass) << "SingleApplication: cannot listen on" << _uniqueKey
229 << ":" << localServer->errorString();
230 // Holding the lock without a server would make every later launch wait
231 // for a server that never comes: no instance could take over while this
232 // one lives. Release it and run without IPC.
233 localServer.reset();
234 _lock.unlock();
235 }
236}
237
239 for (int attempt = 0; attempt < takeoverProbes; ++attempt) {
240 if (peerIsListening()) {
241 _isRunning = true;
242 return;
243 }
244 QThread::msleep(takeoverProbeIntervalMs);
245 }
246 qCDebug(lcQtPass) << "Unable to create single instance.";
247}
248
249auto SingleApplication::forwardMessage(const QString &message) -> bool {
250 QLocalSocket localSocket(this);
251 localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
252 if (!localSocket.waitForConnected(timeout)) {
253 qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
254 return false;
255 }
256 if (!serverRunsAsThisUser(localSocket)) {
257 qCWarning(lcQtPass) << "SingleApplication: the server on" << _uniqueKey
258 << "is not this user's; not forwarding.";
259 localSocket.abort();
260 return false;
261 }
262 QByteArray payload = message.toUtf8();
263 if (payload.isEmpty()) {
264 payload = QByteArray(1, '\0');
265 }
266 localSocket.write(payload);
267 if (!localSocket.waitForBytesWritten(timeout)) {
268 qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
269 return false;
270 }
271 localSocket.disconnectFromServer();
272 return true;
273}
274
276 QLocalSocket probe;
277 probe.connectToServer(_uniqueKey, QIODevice::WriteOnly);
278 if (!probe.waitForConnected(timeout)) {
279 return false;
280 }
281 if (!serverRunsAsThisUser(probe)) {
282 qCWarning(lcQtPass) << "SingleApplication: the server on" << _uniqueKey
283 << "is not this user's.";
284 probe.abort();
285 return false;
286 }
287 probe.disconnectFromServer();
288 return true;
289}
bool _isRunning
true when another instance holds the lock and answers on the socket; this instance should forward and...
auto forwardMessage(const QString &message) -> bool
Deliver a message over the local socket.
void receiveMessage()
Slot for QLocalServer::newConnection: accept every pending connection and emit messageAvailable() wit...
QScopedPointer< QLocalServer > localServer
Server accepting forwarded command lines; only set in the primary instance, null in a secondary or wh...
SingleApplication(int &argc, char *argv[], QString uniqueKey)
Construct a SingleApplication with a unique instance key.
void becomePrimary()
Listen on the key; this instance holds the lock.
QLockFile _lock
Held by the listening instance for as long as it runs.
QString _uniqueKey
Name of the local socket; also names the lock file.
static const int timeout
Milliseconds to wait for a socket connect or write.
auto isRunning() -> bool
Query whether another instance is already running.
static const int maxMessageBytes
Upper bound for one forwarded message (a command line).
static auto privateKey(const QString &base) -> QString
The key to construct with: a socket path in a folder only this user can write to (see privateKeyIn())...
void messageAvailable(const QString &message)
messageAvailable notification from commandline
static auto lockPathFor(const QString &key) -> QString
The lock file that marks the instance listening on key.
static auto privateKeyIn(const QString &base, const QString &dir) -> QString
privateKey() with the folder given.
static const int takeoverProbes
Probes for the lock's holder to start listening before giving up on IPC.
void claimOrFollow()
Take the lock and listen, or become the lock holder's secondary.
static auto serverRunsAsThisUser(const QLocalSocket &socket) -> bool
Whether the server socket is connected to runs as this user.
auto sendMessage(const QString &message) -> bool
Send a message to the running instance.
void waitForPeer()
Become the secondary of the live instance that holds the lock.
auto peerIsListening() -> bool
Probe whether an instance is actually accepting connections.
static const int takeoverProbeIntervalMs
Pause between two takeover probes, in milliseconds.
The "qtpass" logging category.
SingleApplication: a QApplication that keeps one QtPass instance per user via a lock file and forward...