singleapplication_p.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. // The MIT License (MIT)
  2. //
  3. // Copyright (c) Itay Grudev 2015 - 2020
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. // W A R N I N G !!!
  24. // -----------------
  25. //
  26. // This file is not part of the SingleApplication API. It is used purely as an
  27. // implementation detail. This header file may change from version to
  28. // version without notice, or may even be removed.
  29. //
  30. #include <cstdlib>
  31. #include <cstddef>
  32. #include <QtCore/QDir>
  33. #include <QtCore/QThread>
  34. #include <QtCore/QByteArray>
  35. #include <QtCore/QDataStream>
  36. #include <QtCore/QElapsedTimer>
  37. #include <QtCore/QCryptographicHash>
  38. #include <QtNetwork/QLocalServer>
  39. #include <QtNetwork/QLocalSocket>
  40. #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
  41. #include <QtCore/QRandomGenerator>
  42. #else
  43. #include <QtCore/QDateTime>
  44. #endif
  45. #include "singleapplication.h"
  46. #include "singleapplication_p.h"
  47. #ifdef Q_OS_UNIX
  48. #include <unistd.h>
  49. #include <sys/types.h>
  50. #include <pwd.h>
  51. #endif
  52. #ifdef Q_OS_WIN
  53. #ifndef NOMINMAX
  54. #define NOMINMAX 1
  55. #endif
  56. #include <windows.h>
  57. #include <lmcons.h>
  58. #endif
  59. SingleApplicationPrivate::SingleApplicationPrivate( SingleApplication *q_ptr )
  60. : q_ptr( q_ptr )
  61. {
  62. server = nullptr;
  63. socket = nullptr;
  64. memory = nullptr;
  65. instanceNumber = 0;
  66. }
  67. SingleApplicationPrivate::~SingleApplicationPrivate()
  68. {
  69. if( socket != nullptr ){
  70. socket->close();
  71. delete socket;
  72. }
  73. if( memory != nullptr ){
  74. memory->lock();
  75. auto *inst = static_cast<InstancesInfo*>(memory->data());
  76. if( server != nullptr ){
  77. server->close();
  78. delete server;
  79. inst->primary = false;
  80. inst->primaryPid = -1;
  81. inst->primaryUser[0] = '\0';
  82. inst->checksum = blockChecksum();
  83. }
  84. memory->unlock();
  85. delete memory;
  86. }
  87. }
  88. QString SingleApplicationPrivate::getUsername()
  89. {
  90. #ifdef Q_OS_WIN
  91. wchar_t username[UNLEN + 1];
  92. // Specifies size of the buffer on input
  93. DWORD usernameLength = UNLEN + 1;
  94. if( GetUserNameW( username, &usernameLength ) )
  95. return QString::fromWCharArray( username );
  96. #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
  97. return QString::fromLocal8Bit( qgetenv( "USERNAME" ) );
  98. #else
  99. return qEnvironmentVariable( "USERNAME" );
  100. #endif
  101. #endif
  102. #ifdef Q_OS_UNIX
  103. QString username;
  104. uid_t uid = geteuid();
  105. struct passwd *pw = getpwuid( uid );
  106. if( pw )
  107. username = QString::fromLocal8Bit( pw->pw_name );
  108. if ( username.isEmpty() ){
  109. #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
  110. username = QString::fromLocal8Bit( qgetenv( "USER" ) );
  111. #else
  112. username = qEnvironmentVariable( "USER" );
  113. #endif
  114. }
  115. return username;
  116. #endif
  117. }
  118. void SingleApplicationPrivate::genBlockServerName()
  119. {
  120. QCryptographicHash appData( QCryptographicHash::Sha256 );
  121. appData.addData( "SingleApplication", 17 );
  122. appData.addData( SingleApplication::app_t::applicationName().toUtf8() );
  123. appData.addData( SingleApplication::app_t::organizationName().toUtf8() );
  124. appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() );
  125. if ( ! appDataList.isEmpty() )
  126. appData.addData( appDataList.join( "" ).toUtf8() );
  127. if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ){
  128. appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() );
  129. }
  130. if( ! (options & SingleApplication::Mode::ExcludeAppPath) ){
  131. #if defined(Q_OS_WIN)
  132. appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() );
  133. #elif defined(Q_OS_LINUX)
  134. // If the application is running as an AppImage then the APPIMAGE env var should be used
  135. // instead of applicationPath() as each instance is launched with its own executable path
  136. const QByteArray appImagePath = qgetenv( "APPIMAGE" );
  137. if( appImagePath.isEmpty() ){ // Not running as AppImage: use path to executable file
  138. appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
  139. } else { // Running as AppImage: Use absolute path to AppImage file
  140. appData.addData( appImagePath );
  141. };
  142. #else
  143. appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
  144. #endif
  145. }
  146. // User level block requires a user specific data in the hash
  147. if( options & SingleApplication::Mode::User ){
  148. appData.addData( getUsername().toUtf8() );
  149. }
  150. // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with
  151. // server naming requirements.
  152. blockServerName = appData.result().toBase64().replace("/", "_");
  153. }
  154. void SingleApplicationPrivate::initializeMemoryBlock() const
  155. {
  156. auto *inst = static_cast<InstancesInfo*>( memory->data() );
  157. inst->primary = false;
  158. inst->secondary = 0;
  159. inst->primaryPid = -1;
  160. inst->primaryUser[0] = '\0';
  161. inst->checksum = blockChecksum();
  162. }
  163. void SingleApplicationPrivate::startPrimary()
  164. {
  165. // Reset the number of connections
  166. auto *inst = static_cast <InstancesInfo*>( memory->data() );
  167. inst->primary = true;
  168. inst->primaryPid = QCoreApplication::applicationPid();
  169. qstrncpy( inst->primaryUser, getUsername().toUtf8().data(), sizeof(inst->primaryUser) );
  170. inst->checksum = blockChecksum();
  171. instanceNumber = 0;
  172. // Successful creation means that no main process exists
  173. // So we start a QLocalServer to listen for connections
  174. QLocalServer::removeServer( blockServerName );
  175. server = new QLocalServer();
  176. // Restrict access to the socket according to the
  177. // SingleApplication::Mode::User flag on User level or no restrictions
  178. if( options & SingleApplication::Mode::User ){
  179. server->setSocketOptions( QLocalServer::UserAccessOption );
  180. } else {
  181. server->setSocketOptions( QLocalServer::WorldAccessOption );
  182. }
  183. server->listen( blockServerName );
  184. QObject::connect(
  185. server,
  186. &QLocalServer::newConnection,
  187. this,
  188. &SingleApplicationPrivate::slotConnectionEstablished
  189. );
  190. }
  191. void SingleApplicationPrivate::startSecondary()
  192. {
  193. auto *inst = static_cast <InstancesInfo*>( memory->data() );
  194. inst->secondary += 1;
  195. inst->checksum = blockChecksum();
  196. instanceNumber = inst->secondary;
  197. }
  198. bool SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType connectionType )
  199. {
  200. QElapsedTimer time;
  201. time.start();
  202. // Connect to the Local Server of the Primary Instance if not already
  203. // connected.
  204. if( socket == nullptr ){
  205. socket = new QLocalSocket();
  206. }
  207. if( socket->state() == QLocalSocket::ConnectedState ) return true;
  208. if( socket->state() != QLocalSocket::ConnectedState ){
  209. while( true ){
  210. randomSleep();
  211. if( socket->state() != QLocalSocket::ConnectingState )
  212. socket->connectToServer( blockServerName );
  213. if( socket->state() == QLocalSocket::ConnectingState ){
  214. socket->waitForConnected( static_cast<int>(msecs - time.elapsed()) );
  215. }
  216. // If connected break out of the loop
  217. if( socket->state() == QLocalSocket::ConnectedState ) break;
  218. // If elapsed time since start is longer than the method timeout return
  219. if( time.elapsed() >= msecs ) return false;
  220. }
  221. }
  222. // Initialisation message according to the SingleApplication protocol
  223. QByteArray initMsg;
  224. QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
  225. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  226. writeStream.setVersion(QDataStream::Qt_5_6);
  227. #endif
  228. writeStream << blockServerName.toLatin1();
  229. writeStream << static_cast<quint8>(connectionType);
  230. writeStream << instanceNumber;
  231. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  232. quint16 checksum = qChecksum(QByteArray(initMsg, static_cast<quint32>(initMsg.length())));
  233. #else
  234. quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
  235. #endif
  236. writeStream << checksum;
  237. return writeConfirmedMessage( static_cast<int>(msecs - time.elapsed()), initMsg );
  238. }
  239. void SingleApplicationPrivate::writeAck( QLocalSocket *sock ) {
  240. sock->putChar('\n');
  241. }
  242. bool SingleApplicationPrivate::writeConfirmedMessage (int msecs, const QByteArray &msg)
  243. {
  244. QElapsedTimer time;
  245. time.start();
  246. // Frame 1: The header indicates the message length that follows
  247. QByteArray header;
  248. QDataStream headerStream(&header, QIODevice::WriteOnly);
  249. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  250. headerStream.setVersion(QDataStream::Qt_5_6);
  251. #endif
  252. headerStream << static_cast <quint64>( msg.length() );
  253. if( ! writeConfirmedFrame( static_cast<int>(msecs - time.elapsed()), header ))
  254. return false;
  255. // Frame 2: The message
  256. return writeConfirmedFrame( static_cast<int>(msecs - time.elapsed()), msg );
  257. }
  258. bool SingleApplicationPrivate::writeConfirmedFrame( int msecs, const QByteArray &msg )
  259. {
  260. socket->write( msg );
  261. socket->flush();
  262. bool result = socket->waitForReadyRead( msecs ); // await ack byte
  263. if (result) {
  264. socket->read( 1 );
  265. return true;
  266. }
  267. return false;
  268. }
  269. quint16 SingleApplicationPrivate::blockChecksum() const
  270. {
  271. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  272. quint16 checksum = qChecksum(QByteArray(static_cast<const char*>(memory->constData()), offsetof(InstancesInfo, checksum)));
  273. #else
  274. quint16 checksum = qChecksum(static_cast<const char*>(memory->constData()), offsetof(InstancesInfo, checksum));
  275. #endif
  276. return checksum;
  277. }
  278. qint64 SingleApplicationPrivate::primaryPid() const
  279. {
  280. qint64 pid;
  281. memory->lock();
  282. auto *inst = static_cast<InstancesInfo*>( memory->data() );
  283. pid = inst->primaryPid;
  284. memory->unlock();
  285. return pid;
  286. }
  287. QString SingleApplicationPrivate::primaryUser() const
  288. {
  289. QByteArray username;
  290. memory->lock();
  291. auto *inst = static_cast<InstancesInfo*>( memory->data() );
  292. username = inst->primaryUser;
  293. memory->unlock();
  294. return QString::fromUtf8( username );
  295. }
  296. /**
  297. * @brief Executed when a connection has been made to the LocalServer
  298. */
  299. void SingleApplicationPrivate::slotConnectionEstablished()
  300. {
  301. QLocalSocket *nextConnSocket = server->nextPendingConnection();
  302. connectionMap.insert(nextConnSocket, ConnectionInfo());
  303. QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose, this,
  304. [nextConnSocket, this](){
  305. auto &info = connectionMap[nextConnSocket];
  306. this->slotClientConnectionClosed( nextConnSocket, info.instanceId );
  307. }
  308. );
  309. QObject::connect(nextConnSocket, &QLocalSocket::disconnected, nextConnSocket, &QLocalSocket::deleteLater);
  310. QObject::connect(nextConnSocket, &QLocalSocket::destroyed, this,
  311. [nextConnSocket, this](){
  312. connectionMap.remove(nextConnSocket);
  313. }
  314. );
  315. QObject::connect(nextConnSocket, &QLocalSocket::readyRead, this,
  316. [nextConnSocket, this](){
  317. auto &info = connectionMap[nextConnSocket];
  318. switch(info.stage){
  319. case StageInitHeader:
  320. readMessageHeader( nextConnSocket, StageInitBody );
  321. break;
  322. case StageInitBody:
  323. readInitMessageBody(nextConnSocket);
  324. break;
  325. case StageConnectedHeader:
  326. readMessageHeader( nextConnSocket, StageConnectedBody );
  327. break;
  328. case StageConnectedBody:
  329. this->slotDataAvailable( nextConnSocket, info.instanceId );
  330. break;
  331. default:
  332. break;
  333. };
  334. }
  335. );
  336. }
  337. void SingleApplicationPrivate::readMessageHeader( QLocalSocket *sock, SingleApplicationPrivate::ConnectionStage nextStage )
  338. {
  339. if (!connectionMap.contains( sock )){
  340. return;
  341. }
  342. if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ){
  343. return;
  344. }
  345. QDataStream headerStream( sock );
  346. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  347. headerStream.setVersion( QDataStream::Qt_5_6 );
  348. #endif
  349. // Read the header to know the message length
  350. quint64 msgLen = 0;
  351. headerStream >> msgLen;
  352. ConnectionInfo &info = connectionMap[sock];
  353. info.stage = nextStage;
  354. info.msgLen = msgLen;
  355. writeAck( sock );
  356. }
  357. bool SingleApplicationPrivate::isFrameComplete( QLocalSocket *sock )
  358. {
  359. if (!connectionMap.contains( sock )){
  360. return false;
  361. }
  362. ConnectionInfo &info = connectionMap[sock];
  363. if( sock->bytesAvailable() < ( qint64 )info.msgLen ){
  364. return false;
  365. }
  366. return true;
  367. }
  368. void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock )
  369. {
  370. Q_Q(SingleApplication);
  371. if( !isFrameComplete( sock ) )
  372. return;
  373. // Read the message body
  374. QByteArray msgBytes = sock->readAll();
  375. QDataStream readStream(msgBytes);
  376. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  377. readStream.setVersion( QDataStream::Qt_5_6 );
  378. #endif
  379. // server name
  380. QByteArray latin1Name;
  381. readStream >> latin1Name;
  382. // connection type
  383. ConnectionType connectionType = InvalidConnection;
  384. quint8 connTypeVal = InvalidConnection;
  385. readStream >> connTypeVal;
  386. connectionType = static_cast <ConnectionType>( connTypeVal );
  387. // instance id
  388. quint32 instanceId = 0;
  389. readStream >> instanceId;
  390. // checksum
  391. quint16 msgChecksum = 0;
  392. readStream >> msgChecksum;
  393. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  394. const quint16 actualChecksum = qChecksum(QByteArray(msgBytes, static_cast<quint32>(msgBytes.length() - sizeof(quint16))));
  395. #else
  396. const quint16 actualChecksum = qChecksum(msgBytes.constData(), static_cast<quint32>(msgBytes.length() - sizeof(quint16)));
  397. #endif
  398. bool isValid = readStream.status() == QDataStream::Ok &&
  399. QLatin1String(latin1Name) == blockServerName &&
  400. msgChecksum == actualChecksum;
  401. if( !isValid ){
  402. sock->close();
  403. return;
  404. }
  405. ConnectionInfo &info = connectionMap[sock];
  406. info.instanceId = instanceId;
  407. info.stage = StageConnectedHeader;
  408. if( connectionType == NewInstance ||
  409. ( connectionType == SecondaryInstance &&
  410. options & SingleApplication::Mode::SecondaryNotification ) )
  411. {
  412. Q_EMIT q->instanceStarted();
  413. }
  414. writeAck( sock );
  415. }
  416. void SingleApplicationPrivate::slotDataAvailable( QLocalSocket *dataSocket, quint32 instanceId )
  417. {
  418. Q_Q(SingleApplication);
  419. if ( !isFrameComplete( dataSocket ) )
  420. return;
  421. const QByteArray message = dataSocket->readAll();
  422. writeAck( dataSocket );
  423. ConnectionInfo &info = connectionMap[dataSocket];
  424. info.stage = StageConnectedHeader;
  425. Q_EMIT q->receivedMessage( instanceId, message);
  426. }
  427. void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedSocket, quint32 instanceId )
  428. {
  429. if( closedSocket->bytesAvailable() > 0 )
  430. slotDataAvailable( closedSocket, instanceId );
  431. }
  432. void SingleApplicationPrivate::randomSleep()
  433. {
  434. #if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 )
  435. QThread::msleep( QRandomGenerator::global()->bounded( 8u, 18u ));
  436. #else
  437. qsrand( QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max() );
  438. QThread::msleep( qrand() % 11 + 8);
  439. #endif
  440. }
  441. void SingleApplicationPrivate::addAppData(const QString &data)
  442. {
  443. appDataList.push_back(data);
  444. }
  445. QStringList SingleApplicationPrivate::appData() const
  446. {
  447. return appDataList;
  448. }