10#include <QCryptographicHash>
14#include <QLocalSocket>
15#include <QRandomGenerator>
16#include <QSharedPointer>
17#include <QStandardPaths>
27 int &argc,
char *argv[],
29 : QApplication(argc, argv),
_uniqueKey(std::move(uniqueKey)),
33 _lock.setStaleLockTime(0);
42 QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
54 if (dir.isEmpty() || !QFileInfo(dir).isDir()) {
55 qCWarning(lcQtPass) <<
"SingleApplication: no private folder for the"
56 " socket; running without single instance.";
58 QStringLiteral(
"%1").arg(QRandomGenerator::system()->generate64(),
59 16, 16, QLatin1Char(
'0'));
61 const QByteArray hash =
62 QCryptographicHash::hash(base.toUtf8(), QCryptographicHash::Sha256)
65 return QDir(dir).filePath(QStringLiteral(
"qtpass-") +
66 QString::fromLatin1(hash));
77auto tokenUser(HANDLE token) -> std::vector<BYTE> {
79 GetTokenInformation(token, TokenUser,
nullptr, 0, &size);
83 std::vector<BYTE> record(size);
84 if (!GetTokenInformation(token, TokenUser, record.data(), size, &size)) {
95auto processUser(HANDLE process) -> std::vector<BYTE> {
96 HANDLE token =
nullptr;
97 if (!OpenProcessToken(process, TOKEN_QUERY, &token)) {
100 std::vector<BYTE> record = tokenUser(token);
114 const auto pipe =
reinterpret_cast<HANDLE
>(socket.socketDescriptor());
116 if (pipe ==
nullptr || pipe == INVALID_HANDLE_VALUE ||
117 !GetNamedPipeServerProcessId(pipe, &pid)) {
120 HANDLE server = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
121 if (server ==
nullptr) {
124 const std::vector<BYTE> theirs = processUser(server);
126 const std::vector<BYTE> ours = processUser(GetCurrentProcess());
127 if (theirs.empty() || ours.empty()) {
131 reinterpret_cast<const TOKEN_USER *
>(theirs.data())->User.Sid,
132 reinterpret_cast<const TOKEN_USER *
>(ours.data())->User.Sid) !=
141 if (QDir::isAbsolutePath(key)) {
142 return key + QStringLiteral(
".lock");
145 name.replace(QLatin1Char(
'/'), QLatin1Char(
'_'));
146 name.replace(QLatin1Char(
'\\'), QLatin1Char(
'_'));
147 return QDir(QDir::tempPath()).filePath(name + QStringLiteral(
".lock"));
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());
161 localSocket->abort();
164 connect(localSocket, &QLocalSocket::disconnected,
this,
165 [
this, localSocket, buffer]() {
169 if (localSocket->bytesAvailable() > 0) {
170 buffer->append(localSocket->readAll());
172 if (!buffer->isEmpty()) {
175 localSocket->deleteLater();
200 const bool leftOver = QFileInfo::exists(
_lock.fileName());
201 if (
_lock.tryLock(0)) {
204 qCDebug(lcQtPass) <<
"Stale single instance lock, taking over.";
209 if (
_lock.error() != QLockFile::LockFailedError) {
210 qCWarning(lcQtPass) <<
"SingleApplication: cannot take" <<
_lock.fileName()
211 <<
"; running without IPC.";
214 qCDebug(lcQtPass) <<
"Single instance lock held, probing its server.";
224 localServer->setSocketOptions(QLocalServer::UserAccessOption);
225 connect(
localServer.data(), &QLocalServer::newConnection,
this,
228 qCWarning(lcQtPass) <<
"SingleApplication: cannot listen on" <<
_uniqueKey
246 qCDebug(lcQtPass) <<
"Unable to create single instance.";
250 QLocalSocket localSocket(
this);
251 localSocket.connectToServer(
_uniqueKey, QIODevice::WriteOnly);
252 if (!localSocket.waitForConnected(
timeout)) {
253 qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
257 qCWarning(lcQtPass) <<
"SingleApplication: the server on" <<
_uniqueKey
258 <<
"is not this user's; not forwarding.";
262 QByteArray payload = message.toUtf8();
263 if (payload.isEmpty()) {
264 payload = QByteArray(1,
'\0');
266 localSocket.write(payload);
267 if (!localSocket.waitForBytesWritten(
timeout)) {
268 qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
271 localSocket.disconnectFromServer();
277 probe.connectToServer(
_uniqueKey, QIODevice::WriteOnly);
278 if (!probe.waitForConnected(
timeout)) {
282 qCWarning(lcQtPass) <<
"SingleApplication: the server on" <<
_uniqueKey
283 <<
"is not this user's.";
287 probe.disconnectFromServer();
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...