singleapplication_p.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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( ! (options & SingleApplication::Mode::ExcludeAppVersion) ){
  126. appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() );
  127. }
  128. if( ! (options & SingleApplication::Mode::ExcludeAppPath) ){
  129. #ifdef Q_OS_WIN
  130. appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() );
  131. #else
  132. appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
  133. #endif
  134. }
  135. // User level block requires a user specific data in the hash
  136. if( options & SingleApplication::Mode::User ){
  137. appData.addData( getUsername().toUtf8() );
  138. }
  139. // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with
  140. // server naming requirements.
  141. blockServerName = appData.result().toBase64().replace("/", "_");
  142. }
  143. void SingleApplicationPrivate::initializeMemoryBlock() const
  144. {
  145. auto *inst = static_cast<InstancesInfo*>( memory->data() );
  146. inst->primary = false;
  147. inst->secondary = 0;
  148. inst->primaryPid = -1;
  149. inst->primaryUser[0] = '\0';
  150. inst->checksum = blockChecksum();
  151. }
  152. void SingleApplicationPrivate::startPrimary()
  153. {
  154. // Reset the number of connections
  155. auto *inst = static_cast <InstancesInfo*>( memory->data() );
  156. inst->primary = true;
  157. inst->primaryPid = QCoreApplication::applicationPid();
  158. qstrncpy( inst->primaryUser, getUsername().toUtf8().data(), sizeof(inst->primaryUser) );
  159. inst->checksum = blockChecksum();
  160. instanceNumber = 0;
  161. // Successful creation means that no main process exists
  162. // So we start a QLocalServer to listen for connections
  163. QLocalServer::removeServer( blockServerName );
  164. server = new QLocalServer();
  165. // Restrict access to the socket according to the
  166. // SingleApplication::Mode::User flag on User level or no restrictions
  167. if( options & SingleApplication::Mode::User ){
  168. server->setSocketOptions( QLocalServer::UserAccessOption );
  169. } else {
  170. server->setSocketOptions( QLocalServer::WorldAccessOption );
  171. }
  172. server->listen( blockServerName );
  173. QObject::connect(
  174. server,
  175. &QLocalServer::newConnection,
  176. this,
  177. &SingleApplicationPrivate::slotConnectionEstablished
  178. );
  179. }
  180. void SingleApplicationPrivate::startSecondary()
  181. {
  182. auto *inst = static_cast <InstancesInfo*>( memory->data() );
  183. inst->secondary += 1;
  184. inst->checksum = blockChecksum();
  185. instanceNumber = inst->secondary;
  186. }
  187. bool SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType connectionType )
  188. {
  189. QElapsedTimer time;
  190. time.start();
  191. // Connect to the Local Server of the Primary Instance if not already
  192. // connected.
  193. if( socket == nullptr ){
  194. socket = new QLocalSocket();
  195. }
  196. if( socket->state() == QLocalSocket::ConnectedState ) return true;
  197. if( socket->state() != QLocalSocket::ConnectedState ){
  198. while( true ){
  199. randomSleep();
  200. if( socket->state() != QLocalSocket::ConnectingState )
  201. socket->connectToServer( blockServerName );
  202. if( socket->state() == QLocalSocket::ConnectingState ){
  203. socket->waitForConnected( static_cast<int>(msecs - time.elapsed()) );
  204. }
  205. // If connected break out of the loop
  206. if( socket->state() == QLocalSocket::ConnectedState ) break;
  207. // If elapsed time since start is longer than the method timeout return
  208. if( time.elapsed() >= msecs ) return false;
  209. }
  210. }
  211. // Initialisation message according to the SingleApplication protocol
  212. QByteArray initMsg;
  213. QDataStream writeStream(&initMsg, QIODevice::WriteOnly);
  214. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  215. writeStream.setVersion(QDataStream::Qt_5_6);
  216. #endif
  217. writeStream << blockServerName.toLatin1();
  218. writeStream << static_cast<quint8>(connectionType);
  219. writeStream << instanceNumber;
  220. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  221. quint16 checksum = qChecksum(QByteArray(initMsg, static_cast<quint32>(initMsg.length())));
  222. #else
  223. quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
  224. #endif
  225. writeStream << checksum;
  226. // The header indicates the message length that follows
  227. QByteArray header;
  228. QDataStream headerStream(&header, QIODevice::WriteOnly);
  229. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  230. headerStream.setVersion(QDataStream::Qt_5_6);
  231. #endif
  232. headerStream << static_cast <quint64>( initMsg.length() );
  233. socket->write( header );
  234. socket->write( initMsg );
  235. bool result = socket->waitForBytesWritten( static_cast<int>(msecs - time.elapsed()) );
  236. socket->flush();
  237. return result;
  238. }
  239. quint16 SingleApplicationPrivate::blockChecksum() const
  240. {
  241. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  242. quint16 checksum = qChecksum(QByteArray(static_cast<const char*>(memory->constData()), offsetof(InstancesInfo, checksum)));
  243. #else
  244. quint16 checksum = qChecksum(static_cast<const char*>(memory->constData()), offsetof(InstancesInfo, checksum));
  245. #endif
  246. return checksum;
  247. }
  248. qint64 SingleApplicationPrivate::primaryPid() const
  249. {
  250. qint64 pid;
  251. memory->lock();
  252. auto *inst = static_cast<InstancesInfo*>( memory->data() );
  253. pid = inst->primaryPid;
  254. memory->unlock();
  255. return pid;
  256. }
  257. QString SingleApplicationPrivate::primaryUser() const
  258. {
  259. QByteArray username;
  260. memory->lock();
  261. auto *inst = static_cast<InstancesInfo*>( memory->data() );
  262. username = inst->primaryUser;
  263. memory->unlock();
  264. return QString::fromUtf8( username );
  265. }
  266. /**
  267. * @brief Executed when a connection has been made to the LocalServer
  268. */
  269. void SingleApplicationPrivate::slotConnectionEstablished()
  270. {
  271. QLocalSocket *nextConnSocket = server->nextPendingConnection();
  272. connectionMap.insert(nextConnSocket, ConnectionInfo());
  273. QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose,
  274. [nextConnSocket, this](){
  275. auto &info = connectionMap[nextConnSocket];
  276. Q_EMIT this->slotClientConnectionClosed( nextConnSocket, info.instanceId );
  277. }
  278. );
  279. QObject::connect(nextConnSocket, &QLocalSocket::disconnected,
  280. [nextConnSocket, this](){
  281. connectionMap.remove(nextConnSocket);
  282. nextConnSocket->deleteLater();
  283. }
  284. );
  285. QObject::connect(nextConnSocket, &QLocalSocket::readyRead,
  286. [nextConnSocket, this](){
  287. auto &info = connectionMap[nextConnSocket];
  288. switch(info.stage){
  289. case StageHeader:
  290. readInitMessageHeader(nextConnSocket);
  291. break;
  292. case StageBody:
  293. readInitMessageBody(nextConnSocket);
  294. break;
  295. case StageConnected:
  296. Q_EMIT this->slotDataAvailable( nextConnSocket, info.instanceId );
  297. break;
  298. default:
  299. break;
  300. };
  301. }
  302. );
  303. }
  304. void SingleApplicationPrivate::readInitMessageHeader( QLocalSocket *sock )
  305. {
  306. if (!connectionMap.contains( sock )){
  307. return;
  308. }
  309. if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ){
  310. return;
  311. }
  312. QDataStream headerStream( sock );
  313. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  314. headerStream.setVersion( QDataStream::Qt_5_6 );
  315. #endif
  316. // Read the header to know the message length
  317. quint64 msgLen = 0;
  318. headerStream >> msgLen;
  319. ConnectionInfo &info = connectionMap[sock];
  320. info.stage = StageBody;
  321. info.msgLen = msgLen;
  322. if ( sock->bytesAvailable() >= (qint64) msgLen ){
  323. readInitMessageBody( sock );
  324. }
  325. }
  326. void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock )
  327. {
  328. Q_Q(SingleApplication);
  329. if (!connectionMap.contains( sock )){
  330. return;
  331. }
  332. ConnectionInfo &info = connectionMap[sock];
  333. if( sock->bytesAvailable() < ( qint64 )info.msgLen ){
  334. return;
  335. }
  336. // Read the message body
  337. QByteArray msgBytes = sock->read(info.msgLen);
  338. QDataStream readStream(msgBytes);
  339. #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
  340. readStream.setVersion( QDataStream::Qt_5_6 );
  341. #endif
  342. // server name
  343. QByteArray latin1Name;
  344. readStream >> latin1Name;
  345. // connection type
  346. ConnectionType connectionType = InvalidConnection;
  347. quint8 connTypeVal = InvalidConnection;
  348. readStream >> connTypeVal;
  349. connectionType = static_cast <ConnectionType>( connTypeVal );
  350. // instance id
  351. quint32 instanceId = 0;
  352. readStream >> instanceId;
  353. // checksum
  354. quint16 msgChecksum = 0;
  355. readStream >> msgChecksum;
  356. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  357. const quint16 actualChecksum = qChecksum(QByteArray(msgBytes, static_cast<quint32>(msgBytes.length() - sizeof(quint16))));
  358. #else
  359. const quint16 actualChecksum = qChecksum(msgBytes.constData(), static_cast<quint32>(msgBytes.length() - sizeof(quint16)));
  360. #endif
  361. bool isValid = readStream.status() == QDataStream::Ok &&
  362. QLatin1String(latin1Name) == blockServerName &&
  363. msgChecksum == actualChecksum;
  364. if( !isValid ){
  365. sock->close();
  366. return;
  367. }
  368. info.instanceId = instanceId;
  369. info.stage = StageConnected;
  370. if( connectionType == NewInstance ||
  371. ( connectionType == SecondaryInstance &&
  372. options & SingleApplication::Mode::SecondaryNotification ) )
  373. {
  374. Q_EMIT q->instanceStarted();
  375. }
  376. if (sock->bytesAvailable() > 0){
  377. Q_EMIT this->slotDataAvailable( sock, instanceId );
  378. }
  379. }
  380. void SingleApplicationPrivate::slotDataAvailable( QLocalSocket *dataSocket, quint32 instanceId )
  381. {
  382. Q_Q(SingleApplication);
  383. Q_EMIT q->receivedMessage( instanceId, dataSocket->readAll() );
  384. }
  385. void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedSocket, quint32 instanceId )
  386. {
  387. if( closedSocket->bytesAvailable() > 0 )
  388. Q_EMIT slotDataAvailable( closedSocket, instanceId );
  389. }
  390. void SingleApplicationPrivate::randomSleep()
  391. {
  392. #if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 )
  393. QThread::msleep( QRandomGenerator::global()->bounded( 8u, 18u ));
  394. #else
  395. qsrand( QDateTime::currentMSecsSinceEpoch() % std::numeric_limits<uint>::max() );
  396. QThread::msleep( 8 + static_cast <unsigned long>( static_cast <float>( qrand() ) / RAND_MAX * 10 ));
  397. #endif
  398. }