QtPass Developer documentation
QtPass test coverage
Current view: top level - src/singleapplication.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 85.5 % 117 100
Test Date: 2026-12-03 23:34:20 Functions: 93.3 % 15 14
Branches: 87.0 % 54 47

             Branch data     Line data    Source code
       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                 :           8 : SingleApplication::SingleApplication(
      27                 :             :     int &argc, char *argv[], // NOLINT(modernize-avoid-c-arrays)
      28                 :           8 :     QString uniqueKey)
      29                 :             :     : QApplication(argc, argv), _uniqueKey(std::move(uniqueKey)),
      30                 :          16 :       _lock(lockPathFor(_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                 :           8 :   _lock.setStaleLockTime(0);
      34                 :           8 :   claimOrFollow();
      35                 :           8 : }
      36                 :             : 
      37                 :           0 : auto SingleApplication::privateKey(const QString &base) -> QString {
      38                 :             : #ifdef Q_OS_WIN
      39                 :             :   return base;
      40                 :             : #else
      41                 :             :   const QString dir =
      42                 :           0 :       QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
      43         [ #  # ]:           0 :   if (!dir.isEmpty()) {
      44                 :           0 :     QDir().mkpath(dir);
      45                 :             :   }
      46                 :           0 :   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                 :           6 : auto SingleApplication::privateKeyIn(const QString &base, const QString &dir)
      53                 :             :     -> QString {
      54   [ +  +  +  +  :          10 :   if (dir.isEmpty() || !QFileInfo(dir).isDir()) {
                +  +  + ]
      55                 :           4 :     qCWarning(lcQtPass) << "SingleApplication: no private folder for the"
      56                 :           2 :                            " socket; running without single instance.";
      57                 :             :     return base +
      58                 :           6 :            QStringLiteral("%1").arg(QRandomGenerator::system()->generate64(),
      59                 :           2 :                                     16, 16, QLatin1Char('0'));
      60                 :             :   }
      61                 :             :   const QByteArray hash =
      62                 :           4 :       QCryptographicHash::hash(base.toUtf8(), QCryptographicHash::Sha256)
      63                 :           4 :           .toHex()
      64                 :           4 :           .left(16);
      65                 :          12 :   return QDir(dir).filePath(QStringLiteral("qtpass-") +
      66         [ +  + ]:           8 :                             QString::fromLatin1(hash));
      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                 :           9 : auto 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                 :           9 :   return true;
     137                 :             : #endif
     138                 :             : }
     139                 :             : 
     140                 :          21 : auto SingleApplication::lockPathFor(const QString &key) -> QString {
     141         [ +  + ]:          21 :   if (QDir::isAbsolutePath(key)) {
     142                 :           8 :     return key + QStringLiteral(".lock");
     143                 :             :   }
     144                 :             :   QString name = key;
     145                 :          17 :   name.replace(QLatin1Char('/'), QLatin1Char('_'));
     146                 :          17 :   name.replace(QLatin1Char('\\'), QLatin1Char('_'));
     147                 :          51 :   return QDir(QDir::tempPath()).filePath(name + QStringLiteral(".lock"));
     148                 :             : }
     149                 :             : 
     150                 :             : // public slots.
     151                 :             : 
     152                 :          10 : void SingleApplication::receiveMessage() {
     153         [ +  + ]:          20 :   while (QLocalSocket *localSocket = localServer->nextPendingConnection()) {
     154                 :          10 :     auto buffer = QSharedPointer<QByteArray>::create();
     155                 :          10 :     connect(localSocket, &QLocalSocket::readyRead, this,
     156                 :          19 :             [localSocket, buffer]() {
     157                 :          18 :               buffer->append(localSocket->readAll());
     158         [ +  + ]:           9 :               if (buffer->size() > maxMessageBytes) {
     159                 :             :                 // Not a command line any more; drop the peer and its data.
     160                 :           1 :                 buffer->clear();
     161                 :           1 :                 localSocket->abort();
     162                 :             :               }
     163                 :           9 :             });
     164                 :          10 :     connect(localSocket, &QLocalSocket::disconnected, this,
     165                 :          20 :             [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         [ -  + ]:          10 :               if (localSocket->bytesAvailable() > 0) {
     170                 :           0 :                 buffer->append(localSocket->readAll());
     171                 :             :               }
     172         [ +  + ]:          10 :               if (!buffer->isEmpty()) {
     173                 :          12 :                 emit messageAvailable(QString::fromUtf8(buffer->constData()));
     174                 :             :               }
     175                 :          10 :               localSocket->deleteLater();
     176                 :          10 :             });
     177                 :          10 :   }
     178                 :          10 : }
     179                 :             : 
     180                 :             : // public functions.
     181                 :          28 : auto SingleApplication::isRunning() -> bool { return _isRunning; }
     182                 :             : 
     183                 :           6 : auto SingleApplication::sendMessage(const QString &message) -> bool {
     184         [ +  + ]:           6 :   if (!_isRunning) {
     185                 :             :     return false;
     186                 :             :   }
     187         [ +  + ]:           5 :   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                 :           2 :   _isRunning = false;
     194                 :           2 :   claimOrFollow();
     195                 :           2 :   return false;
     196                 :             : }
     197                 :             : 
     198                 :             : // private functions.
     199                 :          10 : void SingleApplication::claimOrFollow() {
     200                 :          10 :   const bool leftOver = QFileInfo::exists(_lock.fileName());
     201         [ +  + ]:          10 :   if (_lock.tryLock(0)) {
     202         [ +  + ]:           4 :     if (leftOver) {
     203                 :             :       // A crash leaves the lock file behind; its process is gone.
     204                 :           2 :       qCDebug(lcQtPass) << "Stale single instance lock, taking over.";
     205                 :             :     }
     206                 :           4 :     becomePrimary();
     207                 :           4 :     return;
     208                 :             :   }
     209         [ -  + ]:           6 :   if (_lock.error() != QLockFile::LockFailedError) {
     210                 :           0 :     qCWarning(lcQtPass) << "SingleApplication: cannot take" << _lock.fileName()
     211                 :           0 :                         << "; running without IPC.";
     212                 :           0 :     return;
     213                 :             :   }
     214                 :          11 :   qCDebug(lcQtPass) << "Single instance lock held, probing its server.";
     215                 :           6 :   waitForPeer();
     216                 :             : }
     217                 :             : 
     218                 :           4 : void SingleApplication::becomePrimary() {
     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                 :           4 :   QLocalServer::removeServer(_uniqueKey);
     223                 :           4 :   localServer.reset(new QLocalServer(this));
     224                 :           4 :   localServer->setSocketOptions(QLocalServer::UserAccessOption);
     225                 :           4 :   connect(localServer.data(), &QLocalServer::newConnection, this,
     226                 :           8 :           &SingleApplication::receiveMessage);
     227         [ +  + ]:           4 :   if (!localServer->listen(_uniqueKey)) {
     228                 :           2 :     qCWarning(lcQtPass) << "SingleApplication: cannot listen on" << _uniqueKey
     229                 :           2 :                         << ":" << 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                 :           1 :     localServer.reset();
     234                 :           1 :     _lock.unlock();
     235                 :             :   }
     236                 :           4 : }
     237                 :             : 
     238                 :           6 : void SingleApplication::waitForPeer() {
     239         [ +  + ]:          11 :   for (int attempt = 0; attempt < takeoverProbes; ++attempt) {
     240         [ +  + ]:          10 :     if (peerIsListening()) {
     241                 :           5 :       _isRunning = true;
     242                 :           5 :       return;
     243                 :             :     }
     244                 :           5 :     QThread::msleep(takeoverProbeIntervalMs);
     245                 :             :   }
     246                 :           2 :   qCDebug(lcQtPass) << "Unable to create single instance.";
     247                 :             : }
     248                 :             : 
     249                 :           5 : auto SingleApplication::forwardMessage(const QString &message) -> bool {
     250                 :           5 :   QLocalSocket localSocket(this);
     251                 :           5 :   localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
     252      [ +  +  + ]:           5 :   if (!localSocket.waitForConnected(timeout)) {
     253                 :           4 :     qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
     254                 :           2 :     return false;
     255                 :             :   }
     256      [ +  -  + ]:           3 :   if (!serverRunsAsThisUser(localSocket)) {
     257                 :           0 :     qCWarning(lcQtPass) << "SingleApplication: the server on" << _uniqueKey
     258                 :           0 :                         << "is not this user's; not forwarding.";
     259                 :           0 :     localSocket.abort();
     260                 :             :     return false;
     261                 :             :   }
     262                 :             :   QByteArray payload = message.toUtf8();
     263         [ +  + ]:           3 :   if (payload.isEmpty()) {
     264                 :           2 :     payload = QByteArray(1, '\0');
     265                 :             :   }
     266                 :           3 :   localSocket.write(payload);
     267      [ +  -  + ]:           3 :   if (!localSocket.waitForBytesWritten(timeout)) {
     268                 :           0 :     qCDebug(lcQtPass) << localSocket.errorString().toLatin1();
     269                 :           0 :     return false;
     270                 :             :   }
     271                 :           3 :   localSocket.disconnectFromServer();
     272                 :             :   return true;
     273                 :           5 : }
     274                 :             : 
     275                 :          10 : auto SingleApplication::peerIsListening() -> bool {
     276                 :          10 :   QLocalSocket probe;
     277                 :          10 :   probe.connectToServer(_uniqueKey, QIODevice::WriteOnly);
     278      [ +  +  + ]:          10 :   if (!probe.waitForConnected(timeout)) {
     279                 :             :     return false;
     280                 :             :   }
     281      [ +  -  + ]:           5 :   if (!serverRunsAsThisUser(probe)) {
     282                 :           0 :     qCWarning(lcQtPass) << "SingleApplication: the server on" << _uniqueKey
     283                 :           0 :                         << "is not this user's.";
     284                 :           0 :     probe.abort();
     285                 :             :     return false;
     286                 :             :   }
     287                 :           5 :   probe.disconnectFromServer();
     288                 :             :   return true;
     289                 :          10 : }
        

Generated by: LCOV version 2.0-1