aboutsummaryrefslogtreecommitdiff
path: root/singleapplication_p.cpp
blob: de4945e5d5de810280ef931ac26d1ebedf269f41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// The MIT License (MIT)
//
// Copyright (c) Itay Grudev 2015 - 2018
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//
//  W A R N I N G !!!
//  -----------------
//
// This file is not part of the SingleApplication API. It is used purely as an
// implementation detail. This header file may change from version to
// version without notice, or may even be removed.
//

#include <cstdlib>
#include <cstddef>

#include <QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QByteArray>
#include <QtCore/QSemaphore>
#include <QtCore/QDataStream>
#include <QtCore/QStandardPaths>
#include <QtCore/QCryptographicHash>
#include <QtNetwork/QLocalServer>
#include <QtNetwork/QLocalSocket>

#include "singleapplication.h"
#include "singleapplication_p.h"

#ifdef Q_OS_WIN
    #include <windows.h>
    #include <lmcons.h>
#endif

SingleApplicationPrivate::SingleApplicationPrivate( SingleApplication *q_ptr )
    : q_ptr( q_ptr )
{
    server = nullptr;
    socket = nullptr;
    memory = nullptr;
    instanceNumber = -1;
}

SingleApplicationPrivate::~SingleApplicationPrivate()
{
    if( socket != nullptr ) {
        socket->close();
        delete socket;
    }

    memory->lock();
    InstancesInfo* inst = static_cast<InstancesInfo*>(memory->data());
    if( server != nullptr ) {
        server->close();
        delete server;
        inst->primary = false;
        inst->primaryPid = -1;
        inst->checksum = blockChecksum();
    }
    memory->unlock();

    delete memory;
}

void SingleApplicationPrivate::genBlockServerName()
{
    QCryptographicHash appData( QCryptographicHash::Sha256 );
    appData.addData( "SingleApplication", 17 );
    appData.addData( SingleApplication::app_t::applicationName().toUtf8() );
    appData.addData( SingleApplication::app_t::organizationName().toUtf8() );
    appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() );

    if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) {
        appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() );
    }

    if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) {
#ifdef Q_OS_WIN
        appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() );
#else
        appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() );
#endif
    }

    // User level block requires a user specific data in the hash
    if( options & SingleApplication::Mode::User ) {
#ifdef Q_OS_WIN
        wchar_t username [ UNLEN + 1 ];
        // Specifies size of the buffer on input
        DWORD usernameLength = UNLEN + 1;
        if( GetUserNameW( username, &usernameLength ) ) {
            appData.addData( QString::fromWCharArray(username).toUtf8() );
        } else {
            appData.addData( QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).join("").toUtf8() );
        }
#endif
#ifdef Q_OS_UNIX
        QProcess process;
        process.start( "whoami" );
        if( process.waitForFinished( 100 ) &&
            process.exitCode() == QProcess::NormalExit) {
            appData.addData( process.readLine() );
        } else {
            appData.addData(
                QDir(
                    QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first()
                ).absolutePath().toUtf8()
            );
        }
#endif
    }

    // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with
    // server naming requirements.
    blockServerName = appData.result().toBase64().replace("/", "_");
}

void SingleApplicationPrivate::initializeMemoryBlock()
{
    InstancesInfo* inst = static_cast<InstancesInfo*>( memory->data() );
    inst->primary = false;
    inst->secondary = 0;
    inst->primaryPid = -1;
    inst->checksum = blockChecksum();
}

void SingleApplicationPrivate::startPrimary()
{
    Q_Q(SingleApplication);

    // Successful creation means that no main process exists
    // So we start a QLocalServer to listen for connections
    QLocalServer::removeServer( blockServerName );
    server = new QLocalServer();

    // Restrict access to the socket according to the
    // SingleApplication::Mode::User flag on User level or no restrictions
    if( options & SingleApplication::Mode::User ) {
      server->setSocketOptions( QLocalServer::UserAccessOption );
    } else {
      server->setSocketOptions( QLocalServer::WorldAccessOption );
    }

    server->listen( blockServerName );
    QObject::connect(
        server,
        &QLocalServer::newConnection,
        this,
        &SingleApplicationPrivate::slotConnectionEstablished
    );

    // Reset the number of connections
    InstancesInfo* inst = static_cast <InstancesInfo*>( memory->data() );

    inst->primary = true;
    inst->primaryPid = q->applicationPid();
    inst->checksum = blockChecksum();

    instanceNumber = 0;
}

void SingleApplicationPrivate::startSecondary()
{
}

void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType connectionType )
{
    // Connect to the Local Server of the Primary Instance if not already
    // connected.
    if( socket == nullptr ) {
        socket = new QLocalSocket();
    }

    // If already connected - we are done;
    if( socket->state() == QLocalSocket::ConnectedState )
        return;

    // If not connect
    if( socket->state() == QLocalSocket::UnconnectedState ||
        socket->state() == QLocalSocket::ClosingState ) {
        socket->connectToServer( blockServerName );
    }

    // Wait for being connected
    if( socket->state() == QLocalSocket::ConnectingState ) {
        socket->waitForConnected( msecs );
    }

    // Initialisation message according to the SingleApplication protocol
    if( socket->state() == QLocalSocket::ConnectedState ) {
        // Notify the parent that a new instance had been started;
        QByteArray initMsg;
        QDataStream writeStream(&initMsg, QIODevice::WriteOnly);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
        writeStream.setVersion(QDataStream::Qt_5_6);
#endif

        writeStream << blockServerName.toLatin1();
        writeStream << static_cast<quint8>(connectionType);
        writeStream << instanceNumber;
        quint16 checksum = qChecksum(initMsg.constData(), static_cast<quint32>(initMsg.length()));
        writeStream << checksum;

        // The header indicates the message length that follows
        QByteArray header;
        QDataStream headerStream(&header, QIODevice::WriteOnly);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
        headerStream.setVersion(QDataStream::Qt_5_6);
#endif
        headerStream << static_cast <quint64>( initMsg.length() );

        socket->write( header );
        socket->write( initMsg );
        socket->flush();
        socket->waitForBytesWritten( msecs );
    }
}

quint16 SingleApplicationPrivate::blockChecksum()
{
    return qChecksum(
       static_cast <const char *>( memory->data() ),
       offsetof( InstancesInfo, checksum )
   );
}

qint64 SingleApplicationPrivate::primaryPid()
{
    qint64 pid;

    memory->lock();
    InstancesInfo* inst = static_cast<InstancesInfo*>( memory->data() );
    pid = inst->primaryPid;
    memory->unlock();

    return pid;
}

/**
 * @brief Executed when a connection has been made to the LocalServer
 */
void SingleApplicationPrivate::slotConnectionEstablished()
{
    QLocalSocket *nextConnSocket = server->nextPendingConnection();
    connectionMap.insert(nextConnSocket, ConnectionInfo());

    QObject::connect(nextConnSocket, &QLocalSocket::aboutToClose,
        [nextConnSocket, this]() {
            auto &info = connectionMap[nextConnSocket];
            Q_EMIT this->slotClientConnectionClosed( nextConnSocket, info.instanceId );
        }
    );

    QObject::connect(nextConnSocket, &QLocalSocket::disconnected,
        [nextConnSocket, this](){
            connectionMap.remove(nextConnSocket);
            nextConnSocket->deleteLater();
        }
    );

    QObject::connect(nextConnSocket, &QLocalSocket::readyRead,
        [nextConnSocket, this]() {
            auto &info = connectionMap[nextConnSocket];
            switch(info.stage) {
            case StageHeader:
                readInitMessageHeader(nextConnSocket);
                break;
            case StageBody:
                readInitMessageBody(nextConnSocket);
                break;
            case StageConnected:
                Q_EMIT this->slotDataAvailable( nextConnSocket, info.instanceId );
                break;
            default:
                break;
            };
        }
    );
}

void SingleApplicationPrivate::readInitMessageHeader( QLocalSocket *sock )
{
    if (!connectionMap.contains( sock )) {
        return;
    }

    if( sock->bytesAvailable() < ( qint64 )sizeof( quint64 ) ) {
        return;
    }

    QDataStream headerStream( sock );

#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    headerStream.setVersion( QDataStream::Qt_5_6 );
#endif

    // Read the header to know the message length
    quint64 msgLen = 0;
    headerStream >> msgLen;
    ConnectionInfo &info = connectionMap[sock];
    info.stage = StageBody;
    info.msgLen = msgLen;

    if ( sock->bytesAvailable() >= (qint64) msgLen ) {
        readInitMessageBody( sock );
    }
}

void SingleApplicationPrivate::readInitMessageBody( QLocalSocket *sock )
{
    Q_Q(SingleApplication);

    if (!connectionMap.contains( sock )) {
        return;
    }

    ConnectionInfo &info = connectionMap[sock];
    if( sock->bytesAvailable() < ( qint64 )info.msgLen ) {
        return;
    }

    // Read the message body
    QByteArray msgBytes = sock->read(info.msgLen);
    QDataStream readStream(msgBytes);

#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
    readStream.setVersion( QDataStream::Qt_5_6 );
#endif

    // server name
    QByteArray latin1Name;
    readStream >> latin1Name;

    // connection type
    ConnectionType connectionType = InvalidConnection;
    quint8 connTypeVal = InvalidConnection;
    readStream >> connTypeVal;
    connectionType = static_cast <ConnectionType>( connTypeVal );

    // instance id
    quint32 instanceId = 0;
    readStream >> instanceId;

    // checksum
    quint16 msgChecksum = 0;
    readStream >> msgChecksum;

    const quint16 actualChecksum = qChecksum( msgBytes.constData(), static_cast<quint32>( msgBytes.length() - sizeof( quint16 ) ) );

    bool isValid = readStream.status() == QDataStream::Ok &&
                   QLatin1String(latin1Name) == blockServerName &&
                   msgChecksum == actualChecksum;

    if( !isValid ) {
        sock->close();
        return;
    }

    info.instanceId = instanceId;
    info.stage = StageConnected;

    if( connectionType == NewInstance ||
        ( connectionType == SecondaryInstance &&
          options & SingleApplication::Mode::SecondaryNotification ) )
    {
        Q_EMIT q->instanceStarted();
    }

    if (sock->bytesAvailable() > 0) {
        Q_EMIT this->slotDataAvailable( sock, instanceId );
    }
}

void SingleApplicationPrivate::slotDataAvailable( QLocalSocket *dataSocket, quint32 instanceId )
{
    Q_Q(SingleApplication);
    Q_EMIT q->receivedMessage( instanceId, dataSocket->readAll() );
}

void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedSocket, quint32 instanceId )
{
    if( closedSocket->bytesAvailable() > 0 )
        Q_EMIT slotDataAvailable( closedSocket, instanceId  );
}