• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 45704487030

25 Nov 2026 09:27PM UTC coverage: 94.806% (-0.05%) from 94.857%
45704487030

push

github

web-flow
Single instance on Windows: forward only to a server of this user (#2341)

#2335 moved the Unix socket into the private runtime folder. On Windows
the named pipe keeps its bare name, and pipe names are machine-wide:
another user's session could open \\.\pipe\<user>QtPass first, and a
launch would forward its command line there and exit without a window.

SingleApplication::serverRunsAsThisUser() looks up the pipe server's
process (GetNamedPipeServerProcessId()) and compares its token's user
with this process's (EqualSid()). peerIsListening() and
forwardMessage() refuse a server that fails it, or that cannot be
checked; the launch then opens its own window. Elsewhere the check is
always true: the socket sits in a folder only this user can open.

The FAQ explains the hand-over and says the Windows case with several
accounts signed in is untested, asking for a report.

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

4 of 10 new or added lines in 1 file covered. (40.0%)

10167 of 10724 relevant lines covered (94.81%)

25998.41 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.32
/src/singleapplication.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements SingleApplication; stale-lock and takeover-race
6
 *        recovery lives in claimOrFollow() and sendMessage().
7
 */
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

26
SingleApplication::SingleApplication(
8 ✔
27
    int &argc, char *argv[], // NOLINT(modernize-avoid-c-arrays)
28
    QString uniqueKey)
8 ✔
29
    : QApplication(argc, argv), _isRunning(false),
8 ✔
30
      _uniqueKey(std::move(uniqueKey)), _lock(lockPathFor(_uniqueKey)) {
16 ✔
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);
8 ✔
34
  claimOrFollow();
8 ✔
35
}
8 ✔
36

37
auto 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.
52
auto SingleApplication::privateKeyIn(const QString &base, const QString &dir)
6 ✔
53
    -> QString {
54
  if (dir.isEmpty() || !QFileInfo(dir).isDir()) {
10 ✔
55
    qCWarning(lcQtPass) << "SingleApplication: no private folder for the"
4 ✔
56
                           " socket; running without single instance.";
2 ✔
57
    return base +
58
           QStringLiteral("%1").arg(QRandomGenerator::system()->generate64(),
6 ✔
59
                                    16, 16, QLatin1Char('0'));
2 ✔
60
  }
61
  const QByteArray hash =
62
      QCryptographicHash::hash(base.toUtf8(), QCryptographicHash::Sha256)
4 ✔
63
          .toHex()
4 ✔
64
          .left(16);
4 ✔
65
  return QDir(dir).filePath(QStringLiteral("qtpass-") +
12 ✔
66
                            QString::fromLatin1(hash));
8 ✔
67
}
68

69
#ifdef Q_OS_WIN
70
namespace {
71

72
/**
73
 * @brief The TOKEN_USER record of @p token, copied out.
74
 * @param token A token opened with TOKEN_QUERY.
75
 * @return The record's bytes; empty when it cannot be read.
76
 */
77
auto 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

90
/**
91
 * @brief The user of process @p process, as a TOKEN_USER record.
92
 * @param process A process handle with query access.
93
 * @return The record's bytes; empty when it cannot be read.
94
 */
95
auto 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.
110
auto SingleApplication::serverRunsAsThisUser(const QLocalSocket &socket)
9 ✔
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;
9 ✔
137
#endif
138
}
139

140
auto SingleApplication::lockPathFor(const QString &key) -> QString {
21 ✔
141
  if (QDir::isAbsolutePath(key)) {
21 ✔
142
    return key + QStringLiteral(".lock");
8 ✔
143
  }
144
  QString name = key;
145
  name.replace(QLatin1Char('/'), QLatin1Char('_'));
17 ✔
146
  name.replace(QLatin1Char('\\'), QLatin1Char('_'));
17 ✔
147
  return QDir(QDir::tempPath()).filePath(name + QStringLiteral(".lock"));
51 ✔
148
}
149

150
// public slots.
151

152
void SingleApplication::receiveMessage() {
10 ✔
153
  while (QLocalSocket *localSocket = localServer->nextPendingConnection()) {
20 ✔
154
    auto buffer = QSharedPointer<QByteArray>::create();
10 ✔
155
    connect(localSocket, &QLocalSocket::readyRead, this,
10 ✔
156
            [localSocket, buffer]() {
19 ✔
157
              buffer->append(localSocket->readAll());
18 ✔
158
              if (buffer->size() > maxMessageBytes) {
9 ✔
159
                // Not a command line any more; drop the peer and its data.
160
                buffer->clear();
1 ✔
161
                localSocket->abort();
1 ✔
162
              }
163
            });
9 ✔
164
    connect(localSocket, &QLocalSocket::disconnected, this,
10 ✔
165
            [this, localSocket, buffer]() {
30 ✔
166
              buffer->append(localSocket->readAll());
20 ✔
167
              if (!buffer->isEmpty()) {
10 ✔
168
                emit messageAvailable(QString::fromUtf8(buffer->constData()));
12 ✔
169
              }
170
              localSocket->deleteLater();
10 ✔
171
            });
10 ✔
172
  }
10 ✔
173
}
10 ✔
174

175
// public functions.
176
auto SingleApplication::isRunning() -> bool { return _isRunning; }
28 ✔
177

178
auto SingleApplication::sendMessage(const QString &message) -> bool {
6 ✔
179
  if (!_isRunning) {
6 ✔
180
    return false;
181
  }
182
  if (forwardMessage(message)) {
5 ✔
183
    return true;
184
  }
185
  // The peer vanished between the probe in the constructor and now. Take its
186
  // lock and its place, so the window main() opens next is the reachable
187
  // instance; if it still holds the lock, it may be restarting its server.
188
  _isRunning = false;
2 ✔
189
  claimOrFollow();
2 ✔
190
  return false;
2 ✔
191
}
192

193
// private functions.
194
void SingleApplication::claimOrFollow() {
10 ✔
195
  const bool leftOver = QFileInfo::exists(_lock.fileName());
10 ✔
196
  if (_lock.tryLock(0)) {
10 ✔
197
    if (leftOver) {
4 ✔
198
      // A crash leaves the lock file behind; its process is gone.
199
      qCDebug(lcQtPass) << "Stale single instance lock, taking over.";
2 ✔
200
    }
201
    becomePrimary();
4 ✔
202
    return;
4 ✔
203
  }
204
  if (_lock.error() != QLockFile::LockFailedError) {
6 ✔
205
    qCWarning(lcQtPass) << "SingleApplication: cannot take" << _lock.fileName()
×
206
                        << "; running without IPC.";
×
207
    return;
×
208
  }
209
  qCDebug(lcQtPass) << "Single instance lock held, probing its server.";
11 ✔
210
  waitForPeer();
6 ✔
211
}
212

213
void SingleApplication::becomePrimary() {
4 ✔
214
  // A socket file left behind by a crashed instance would make listen() fail
215
  // (address in use) and silently disable IPC for good, so clear it first:
216
  // this instance holds the lock, so no live instance listens on it.
217
  QLocalServer::removeServer(_uniqueKey);
4 ✔
218
  localServer.reset(new QLocalServer(this));
4 ✔
219
  localServer->setSocketOptions(QLocalServer::UserAccessOption);
4 ✔
220
  connect(localServer.data(), &QLocalServer::newConnection, this,
4 ✔
221
          &SingleApplication::receiveMessage);
8 ✔
222
  if (!localServer->listen(_uniqueKey)) {
4 ✔
223
    qCWarning(lcQtPass) << "SingleApplication: cannot listen on" << _uniqueKey
2 ✔
224
                        << ":" << localServer->errorString();
2 ✔
225
    // Holding the lock without a server would make every later launch wait
226
    // for a server that never comes: no instance could take over while this
227
    // one lives. Release it and run without IPC.
228
    localServer.reset();
1 ✔
229
    _lock.unlock();
1 ✔
230
  }
231
}
4 ✔
232

233
void SingleApplication::waitForPeer() {
6 ✔
234
  for (int attempt = 0; attempt < takeoverProbes; ++attempt) {
11 ✔
235
    if (peerIsListening()) {
10 ✔
236
      _isRunning = true;
5 ✔
237
      return;
5 ✔
238
    }
239
    QThread::msleep(takeoverProbeIntervalMs);
5 ✔
240
  }
241
  qCDebug(lcQtPass) << "Unable to create single instance.";
2 ✔
242
}
243

244
auto SingleApplication::forwardMessage(const QString &message) -> bool {
5 ✔
245
  QLocalSocket localSocket(this);
5 ✔
246
  localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
5 ✔
247
  if (!localSocket.waitForConnected(timeout)) {
5 ✔
248
    qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
4 ✔
249
    return false;
2 ✔
250
  }
251
  if (!serverRunsAsThisUser(localSocket)) {
3 ✔
NEW
252
    qCWarning(lcQtPass) << "SingleApplication: the server on" << _uniqueKey
×
NEW
253
                        << "is not this user's; not forwarding.";
×
NEW
254
    localSocket.abort();
×
255
    return false;
256
  }
257
  QByteArray payload = message.toUtf8();
258
  if (payload.isEmpty()) {
3 ✔
259
    payload = QByteArray(1, '\0');
2 ✔
260
  }
261
  localSocket.write(payload);
3 ✔
262
  if (!localSocket.waitForBytesWritten(timeout)) {
3 ✔
263
    qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
×
264
    return false;
×
265
  }
266
  localSocket.disconnectFromServer();
3 ✔
267
  return true;
268
}
5 ✔
269

270
auto SingleApplication::peerIsListening() -> bool {
10 ✔
271
  QLocalSocket probe;
10 ✔
272
  probe.connectToServer(_uniqueKey, QIODevice::WriteOnly);
10 ✔
273
  if (!probe.waitForConnected(timeout)) {
10 ✔
274
    return false;
275
  }
276
  if (!serverRunsAsThisUser(probe)) {
5 ✔
NEW
277
    qCWarning(lcQtPass) << "SingleApplication: the server on" << _uniqueKey
×
NEW
278
                        << "is not this user's.";
×
NEW
279
    probe.abort();
×
280
    return false;
281
  }
282
  probe.disconnectFromServer();
5 ✔
283
  return true;
284
}
10 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc