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

IJHack / QtPass / 45587053559

25 Nov 2026 09:36AM UTC coverage: 94.8% (-0.04%) from 94.835%
45587053559

Pull #2335

github

web-flow
Merge 4149c21c5 into 245c1af9c
Pull Request #2335: Single instance: name the IPC objects with a suffix only this user knows

39 of 45 new or added lines in 1 file covered. (86.67%)

5 existing lines in 1 file now uncovered.

10045 of 10596 relevant lines covered (94.8%)

21778.51 hits per line

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

92.86
/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-segment and takeover-race
6
 *        recovery lives in the constructor and becomePrimary().
7
 */
8
#include "singleapplication.h"
9
#include "qtpasslogging.h"
10
#include <QCryptographicHash>
11
#include <QDebug>
12
#include <QDir>
13
#include <QFile>
14
#include <QLocalSocket>
15
#include <QRandomGenerator>
16
#include <QRegularExpression>
17
#include <QSharedPointer>
18
#include <QStandardPaths>
19
#include <QTemporaryFile>
20
#include <QThread>
21
#include <utility>
22

23
namespace {
24

25
/**
26
 * @brief A fresh random suffix for privateKeyIn().
27
 * @return SingleApplication::privateSuffixLength lowercase hex digits.
28
 */
29
auto randomSuffix() -> QString {
7 ✔
30
  static_assert(SingleApplication::privateSuffixLength == 16,
31
                "one 64-bit number in hex");
32
  return QStringLiteral("%1").arg(QRandomGenerator::system()->generate64(),
7 ✔
33
                                  SingleApplication::privateSuffixLength, 16,
34
                                  QLatin1Char('0'));
21 ✔
35
}
36

37
/**
38
 * @brief Read a suffix privateKeyIn() wrote earlier.
39
 * @param path The suffix file.
40
 * @return The suffix, or an empty string when the file is missing or does
41
 *         not hold exactly one.
42
 */
43
auto readSuffix(const QString &path) -> QString {
7 ✔
44
  QFile file(path);
7 ✔
45
  if (!file.open(QIODevice::ReadOnly)) {
7 ✔
46
    return {};
4 ✔
47
  }
48
  const QString text =
49
      QString::fromLatin1(file.read(SingleApplication::privateSuffixLength + 2))
3 ✔
50
          .trimmed();
51
  static const QRegularExpression hex(QRegularExpression::anchoredPattern(
1 ✔
52
      QStringLiteral("[0-9a-f]{%1}")
1 ✔
53
          .arg(SingleApplication::privateSuffixLength)));
4 ✔
54
  return hex.match(text).hasMatch() ? text : QString();
5 ✔
55
}
7 ✔
56

57
/**
58
 * @brief Write @p suffix to @p path unless a file is there already.
59
 *
60
 * Written to a temporary file next to it (mode 0600) and renamed into place
61
 * without replacing: of two launches writing at once, one file wins and the
62
 * other launch reads it.
63
 * @param path The suffix file.
64
 * @param suffix The suffix to keep.
65
 * @return true when this call put the file in place.
66
 */
67
auto writeSuffix(const QString &path, const QString &suffix) -> bool {
5 ✔
68
  QTemporaryFile file(path + QStringLiteral(".XXXXXX"));
10 ✔
69
  if (!file.open() || file.write(suffix.toLatin1()) != suffix.size() ||
20 ✔
70
      !file.flush()) {
5 ✔
71
    return false;
72
  }
73
  if (!file.rename(path)) {
5 ✔
74
    return false;
75
  }
76
  file.setAutoRemove(false);
5 ✔
77
  return true;
78
}
5 ✔
79

80
} // namespace
81

82
SingleApplication::SingleApplication(
6 ✔
83
    int &argc, char *argv[], // NOLINT(modernize-avoid-c-arrays)
84
    QString uniqueKey)
6 ✔
85
    : QApplication(argc, argv), _isRunning(false),
6 ✔
86
      _uniqueKey(std::move(uniqueKey)) {
6 ✔
87
  sharedMemory.setKey(_uniqueKey);
6 ✔
88
  if (sharedMemory.attach()) {
6 ✔
89
    if (peerIsListening()) {
5 ✔
90
      _isRunning = true;
3 ✔
91
      return;
3 ✔
92
    }
93
    // The segment outlived the instance that created it (a crash leaves
94
    // System V shared memory behind on Unix). Nobody answers on the socket,
95
    // so take over instead of forwarding into the void forever.
96
    qCDebug(lcQtPass) << "Stale single instance segment, taking over.";
4 ✔
97
    sharedMemory.detach();
2 ✔
98
  }
99
  becomePrimary();
3 ✔
UNCOV
100
}
×
101

NEW
UNCOV
102
auto SingleApplication::privateKey(const QString &base) -> QString {
×
103
#ifdef Q_OS_WIN
104
  const QString dir = QDir::tempPath();
105
#else
106
  const QString dir =
NEW
UNCOV
107
      QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
×
108
#endif
NEW
109
  return privateKeyIn(base, dir);
×
110
}
111

112
// The suffix file is named after a hash of the base, so any login name
113
// makes a valid file name.
114
auto SingleApplication::privateKeyIn(const QString &base, const QString &dir)
9 ✔
115
    -> QString {
116
  if (dir.isEmpty() || !QDir(dir).exists()) {
16 ✔
117
    qCWarning(lcQtPass) << "SingleApplication: no private folder for the"
4 ✔
118
                           " instance key; running without single instance.";
2 ✔
119
    return base + randomSuffix();
4 ✔
120
  }
121
  const QString path = QDir(dir).filePath(
7 ✔
122
      QStringLiteral("qtpass-instance-") +
7 ✔
123
      QString::fromLatin1(
7 ✔
124
          QCryptographicHash::hash(base.toUtf8(), QCryptographicHash::Sha256)
7 ✔
125
              .toHex()
7 ✔
126
              .left(16)));
21 ✔
127
  QString suffix = readSuffix(path);
7 ✔
128
  if (suffix.isEmpty()) {
7 ✔
129
    // Not written yet, or not one we wrote: put a new one in place. A file
130
    // that holds anything else is replaced, as nothing can use it.
131
    if (QFile::exists(path)) {
5 ✔
132
      QFile::remove(path);
1 ✔
133
    }
134
    const QString fresh = randomSuffix();
5 ✔
135
    suffix = writeSuffix(path, fresh) ? fresh : readSuffix(path);
15 ✔
136
  }
137
  if (suffix.isEmpty()) {
7 ✔
NEW
138
    qCWarning(lcQtPass) << "SingleApplication: cannot keep the instance key in"
×
NEW
139
                        << dir << "; running without single instance.";
×
NEW
140
    return base + randomSuffix();
×
141
  }
142
  return base + suffix;
7 ✔
143
}
144

145
// public slots.
146

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

170
// public functions.
171
auto SingleApplication::isRunning() -> bool { return _isRunning; }
24 ✔
172

173
auto SingleApplication::sendMessage(const QString &message) -> bool {
5 ✔
174
  if (!_isRunning) {
5 ✔
175
    return false;
176
  }
177
  if (forwardMessage(message)) {
4 ✔
178
    return true;
179
  }
180
  // The peer vanished between the probe in the constructor and now. Let go of
181
  // its segment and take its place, so the window main() opens next is the
182
  // reachable instance. Staying attached without listening would make every
183
  // later launch fail create() and open yet another window without IPC.
184
  _isRunning = false;
2 ✔
185
  sharedMemory.detach();
2 ✔
186
  becomePrimary();
2 ✔
187
  return false;
2 ✔
188
}
189

190
// private functions.
191
void SingleApplication::becomePrimary() {
5 ✔
192
  // create shared memory.
193
  if (!sharedMemory.create(1)) {
5 ✔
194
    // Another launch claimed the segment first (two launchers recovering
195
    // from the same crash). Give it a moment to start listening and become
196
    // its secondary, so main() forwards instead of opening a second window.
197
    if (sharedMemory.attach()) {
2 ✔
198
      for (int attempt = 0; attempt < takeoverProbes; ++attempt) {
7 ✔
199
        if (peerIsListening()) {
6 ✔
200
          _isRunning = true;
1 ✔
201
          return;
1 ✔
202
        }
203
        QThread::msleep(takeoverProbeIntervalMs);
5 ✔
204
      }
205
      sharedMemory.detach();
1 ✔
206
    }
207
    qCDebug(lcQtPass) << "Unable to create single instance.";
2 ✔
208
    return;
1 ✔
209
  }
210
  // create local server and listen to incoming messages from other
211
  // instances. A socket file left behind by a crashed instance would make
212
  // listen() fail (address in use) and silently disable IPC for good, so
213
  // clear it first: no live peer answered on it, or create() would have
214
  // failed.
215
  QLocalServer::removeServer(_uniqueKey);
3 ✔
216
  localServer.reset(new QLocalServer(this));
3 ✔
217
  localServer->setSocketOptions(QLocalServer::UserAccessOption);
3 ✔
218
  connect(localServer.data(), &QLocalServer::newConnection, this,
3 ✔
219
          &SingleApplication::receiveMessage);
6 ✔
220
  if (!localServer->listen(_uniqueKey)) {
3 ✔
221
    qCWarning(lcQtPass) << "SingleApplication: cannot listen on" << _uniqueKey
2 ✔
222
                        << ":" << localServer->errorString();
2 ✔
223
    // Holding the segment without a server would make every later launch
224
    // attach, fail the probe and then fail create(): no instance could ever
225
    // take over while this one lives. Release it and run without IPC.
226
    localServer.reset();
1 ✔
227
    sharedMemory.detach();
1 ✔
228
  }
229
}
230

231
auto SingleApplication::forwardMessage(const QString &message) -> bool {
4 ✔
232
  QLocalSocket localSocket(this);
4 ✔
233
  localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
4 ✔
234
  if (!localSocket.waitForConnected(timeout)) {
4 ✔
235
    qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
4 ✔
236
    return false;
2 ✔
237
  }
238
  QByteArray payload = message.toUtf8();
239
  if (payload.isEmpty()) {
2 ✔
240
    payload = QByteArray(1, '\0');
2 ✔
241
  }
242
  localSocket.write(payload);
2 ✔
243
  if (!localSocket.waitForBytesWritten(timeout)) {
2 ✔
UNCOV
244
    qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
×
UNCOV
245
    return false;
×
246
  }
247
  localSocket.disconnectFromServer();
2 ✔
248
  return true;
249
}
4 ✔
250

251
auto SingleApplication::peerIsListening() -> bool {
11 ✔
252
  QLocalSocket probe;
11 ✔
253
  probe.connectToServer(_uniqueKey, QIODevice::WriteOnly);
11 ✔
254
  if (!probe.waitForConnected(timeout)) {
11 ✔
255
    return false;
256
  }
257
  probe.disconnectFromServer();
4 ✔
258
  return true;
259
}
11 ✔
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