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

IJHack / QtPass / 45595417495

25 Nov 2026 10:29AM UTC coverage: 94.781% (-0.05%) from 94.835%
45595417495

push

github

web-flow
Single instance: socket and lock in the private runtime folder (#2335)

The single-instance segment, its semaphore and the local socket were
named after $USER + "QtPass", and on Linux and BSD those names resolve
into the shared /tmp. Another local user who knows the login name could
create them first: a 0666 segment plus a listening socket made every
launch forward its command line to that user and exit without a
window, and a semaphore left at 0 made every launch hang in attach().

SingleApplication::privateKey() now gives a socket path in
QStandardPaths::RuntimeLocation (0700, refused by Qt when another user
owns it), so nobody else can see or create anything there. The shared
memory segment is gone: a QLockFile next to the socket marks the
listening instance. A free or stale lock (its process gone) is taken
and the instance listens; a lock held by a live instance makes this one
probe its socket, as before; listen() failing releases the lock.
Without a private folder the key is the base plus a random suffix, so
the launch runs as its own instance instead of on a guessable name.
Windows keeps the bare pipe name; its lock sits in the per-user
temporary folder.

Scan: ANT-2026-1JUBRKLZ

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

41 of 49 new or added lines in 1 file covered. (83.67%)

10025 of 10577 relevant lines covered (94.78%)

21818.08 hits per line

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

90.65
/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
SingleApplication::SingleApplication(
8 ✔
22
    int &argc, char *argv[], // NOLINT(modernize-avoid-c-arrays)
23
    QString uniqueKey)
8 ✔
24
    : QApplication(argc, argv), _isRunning(false),
8 ✔
25
      _uniqueKey(std::move(uniqueKey)), _lock(lockPathFor(_uniqueKey)) {
16 ✔
26
  // Stale only when its process is gone: a running instance holds the lock
27
  // for as long as it runs, far beyond any age limit.
28
  _lock.setStaleLockTime(0);
8 ✔
29
  claimOrFollow();
8 ✔
30
}
8 ✔
31

NEW
32
auto SingleApplication::privateKey(const QString &base) -> QString {
×
33
#ifdef Q_OS_WIN
34
  return base;
35
#else
36
  const QString dir =
NEW
37
      QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
×
NEW
38
  if (!dir.isEmpty()) {
×
NEW
39
    QDir().mkpath(dir);
×
40
  }
NEW
41
  return privateKeyIn(base, dir);
×
42
#endif
43
}
44

45
// Named after a hash of the base, so any login name makes a valid file name
46
// and the path stays well under the 104 bytes macOS allows a socket path.
47
auto SingleApplication::privateKeyIn(const QString &base, const QString &dir)
6 ✔
48
    -> QString {
49
  if (dir.isEmpty() || !QFileInfo(dir).isDir()) {
10 ✔
50
    qCWarning(lcQtPass) << "SingleApplication: no private folder for the"
4 ✔
51
                           " socket; running without single instance.";
2 ✔
52
    return base +
53
           QStringLiteral("%1").arg(QRandomGenerator::system()->generate64(),
6 ✔
54
                                    16, 16, QLatin1Char('0'));
2 ✔
55
  }
56
  const QByteArray hash =
57
      QCryptographicHash::hash(base.toUtf8(), QCryptographicHash::Sha256)
4 ✔
58
          .toHex()
4 ✔
59
          .left(16);
4 ✔
60
  return QDir(dir).filePath(QStringLiteral("qtpass-") +
12 ✔
61
                            QString::fromLatin1(hash));
8 ✔
62
}
63

64
auto SingleApplication::lockPathFor(const QString &key) -> QString {
21 ✔
65
  if (QDir::isAbsolutePath(key)) {
21 ✔
66
    return key + QStringLiteral(".lock");
8 ✔
67
  }
68
  QString name = key;
69
  name.replace(QLatin1Char('/'), QLatin1Char('_'));
17 ✔
70
  name.replace(QLatin1Char('\\'), QLatin1Char('_'));
17 ✔
71
  return QDir(QDir::tempPath()).filePath(name + QStringLiteral(".lock"));
51 ✔
72
}
73

74
// public slots.
75

76
void SingleApplication::receiveMessage() {
9 ✔
77
  while (QLocalSocket *localSocket = localServer->nextPendingConnection()) {
18 ✔
78
    auto buffer = QSharedPointer<QByteArray>::create();
9 ✔
79
    connect(localSocket, &QLocalSocket::readyRead, this,
9 ✔
80
            [localSocket, buffer]() {
18 ✔
81
              buffer->append(localSocket->readAll());
18 ✔
82
              if (buffer->size() > maxMessageBytes) {
9 ✔
83
                // Not a command line any more; drop the peer and its data.
84
                buffer->clear();
1 ✔
85
                localSocket->abort();
1 ✔
86
              }
87
            });
9 ✔
88
    connect(localSocket, &QLocalSocket::disconnected, this,
9 ✔
89
            [this, localSocket, buffer]() {
27 ✔
90
              buffer->append(localSocket->readAll());
18 ✔
91
              if (!buffer->isEmpty()) {
9 ✔
92
                emit messageAvailable(QString::fromUtf8(buffer->constData()));
12 ✔
93
              }
94
              localSocket->deleteLater();
9 ✔
95
            });
9 ✔
96
  }
9 ✔
97
}
9 ✔
98

99
// public functions.
100
auto SingleApplication::isRunning() -> bool { return _isRunning; }
27 ✔
101

102
auto SingleApplication::sendMessage(const QString &message) -> bool {
6 ✔
103
  if (!_isRunning) {
6 ✔
104
    return false;
105
  }
106
  if (forwardMessage(message)) {
5 ✔
107
    return true;
108
  }
109
  // The peer vanished between the probe in the constructor and now. Take its
110
  // lock and its place, so the window main() opens next is the reachable
111
  // instance; if it still holds the lock, it may be restarting its server.
112
  _isRunning = false;
2 ✔
113
  claimOrFollow();
2 ✔
114
  return false;
2 ✔
115
}
116

117
// private functions.
118
void SingleApplication::claimOrFollow() {
10 ✔
119
  const bool leftOver = QFileInfo::exists(_lock.fileName());
10 ✔
120
  if (_lock.tryLock(0)) {
10 ✔
121
    if (leftOver) {
4 ✔
122
      // A crash leaves the lock file behind; its process is gone.
123
      qCDebug(lcQtPass) << "Stale single instance lock, taking over.";
2 ✔
124
    }
125
    becomePrimary();
4 ✔
126
    return;
4 ✔
127
  }
128
  if (_lock.error() != QLockFile::LockFailedError) {
6 ✔
NEW
129
    qCWarning(lcQtPass) << "SingleApplication: cannot take" << _lock.fileName()
×
NEW
130
                        << "; running without IPC.";
×
NEW
131
    return;
×
132
  }
133
  qCDebug(lcQtPass) << "Single instance lock held, probing its server.";
11 ✔
134
  waitForPeer();
6 ✔
135
}
136

137
void SingleApplication::becomePrimary() {
4 ✔
138
  // A socket file left behind by a crashed instance would make listen() fail
139
  // (address in use) and silently disable IPC for good, so clear it first:
140
  // this instance holds the lock, so no live instance listens on it.
141
  QLocalServer::removeServer(_uniqueKey);
4 ✔
142
  localServer.reset(new QLocalServer(this));
4 ✔
143
  localServer->setSocketOptions(QLocalServer::UserAccessOption);
4 ✔
144
  connect(localServer.data(), &QLocalServer::newConnection, this,
4 ✔
145
          &SingleApplication::receiveMessage);
8 ✔
146
  if (!localServer->listen(_uniqueKey)) {
4 ✔
147
    qCWarning(lcQtPass) << "SingleApplication: cannot listen on" << _uniqueKey
2 ✔
148
                        << ":" << localServer->errorString();
2 ✔
149
    // Holding the lock without a server would make every later launch wait
150
    // for a server that never comes: no instance could take over while this
151
    // one lives. Release it and run without IPC.
152
    localServer.reset();
1 ✔
153
    _lock.unlock();
1 ✔
154
  }
155
}
4 ✔
156

157
void SingleApplication::waitForPeer() {
6 ✔
158
  for (int attempt = 0; attempt < takeoverProbes; ++attempt) {
11 ✔
159
    if (peerIsListening()) {
10 ✔
160
      _isRunning = true;
5 ✔
161
      return;
5 ✔
162
    }
163
    QThread::msleep(takeoverProbeIntervalMs);
5 ✔
164
  }
165
  qCDebug(lcQtPass) << "Unable to create single instance.";
2 ✔
166
}
167

168
auto SingleApplication::forwardMessage(const QString &message) -> bool {
5 ✔
169
  QLocalSocket localSocket(this);
5 ✔
170
  localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
5 ✔
171
  if (!localSocket.waitForConnected(timeout)) {
5 ✔
172
    qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
4 ✔
173
    return false;
2 ✔
174
  }
175
  QByteArray payload = message.toUtf8();
176
  if (payload.isEmpty()) {
3 ✔
177
    payload = QByteArray(1, '\0');
2 ✔
178
  }
179
  localSocket.write(payload);
3 ✔
180
  if (!localSocket.waitForBytesWritten(timeout)) {
3 ✔
181
    qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
×
182
    return false;
×
183
  }
184
  localSocket.disconnectFromServer();
3 ✔
185
  return true;
186
}
5 ✔
187

188
auto SingleApplication::peerIsListening() -> bool {
10 ✔
189
  QLocalSocket probe;
10 ✔
190
  probe.connectToServer(_uniqueKey, QIODevice::WriteOnly);
10 ✔
191
  if (!probe.waitForConnected(timeout)) {
10 ✔
192
    return false;
193
  }
194
  probe.disconnectFromServer();
5 ✔
195
  return true;
196
}
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