Debian Codegraph @

thirdparty/qtsingleapplication/src/qtlocalpeer.cpp

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the Qt Solutions component.
7 **
8 ** $QT_BEGIN_LICENSE:BSD$
9 ** You may use this file under the terms of the BSD license as follows:
10 **
11 ** "Redistribution and use in source and binary forms, with or without
12 ** modification, are permitted provided that the following conditions are
13 ** met:
14 ** * Redistributions of source code must retain the above copyright
15 ** notice, this list of conditions and the following disclaimer.
16 ** * Redistributions in binary form must reproduce the above copyright
17 ** notice, this list of conditions and the following disclaimer in
18 ** the documentation and/or other materials provided with the
19 ** distribution.
20 ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
21 ** of its contributors may be used to endorse or promote products derived
22 ** from this software without specific prior written permission.
23 **
24 **
25 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41
42 #include "qtlocalpeer.h"
43 #include <QCoreApplication>
44 #include <QDataStream>
45
46
47 #if defined( Q_OS_WIN )
48 #include <qt_windows.h>
49 #endif
50
51 #if defined(Q_OS_UNIX)
52 #include <ctime>
53 #include <unistd.h>
54 #endif
55
56 #include <QRegularExpression>
57
58
59 const char* QtLocalPeer::ack = "ack";
60
61 QtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)
62 : QObject(parent), id(appId)
63 {
64 if (id.isEmpty()) {
65 id = QCoreApplication::applicationName();
66 }
67 QString prefix = id;
68 #if defined( Q_OS_WIN )
69 prefix = prefix.toLower();
70 #endif
71
72 prefix.remove(QRegularExpression("[^a-zA-Z]"));
73 prefix.truncate(6);
74
75 QByteArray idc = QDir::home().dirName().toUtf8();
76 #if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
77 quint16 idNum = qChecksum( idc.constData(), idc.size() );
78 #else
79 quint16 idNum = qChecksum( idc );
80 #endif
81
82 socketName = QLatin1String("single-") + prefix
83 + QLatin1Char('-') + QString::number(idNum, 16);
84
85 server = new QLocalServer(this);
86 QString lockName = QDir(QDir::tempPath()).absolutePath()
87 + QLatin1Char('/') + socketName
88 + QLatin1String("-gdlockfile");
89 lockFile = new QLockFile(lockName);
90 lockFile->setStaleLockTime(0);
91 if ( !lockFile->tryLock( 0 ) ) {
92 if ( lockFile->error() != QLockFile::NoError && lockFile->error() != QLockFile::LockFailedError ) {
93 qWarning() << "QLockFile error: " << lockFile->error();
94 }
95 }
96 }
97
98 bool QtLocalPeer::isClient()
99 {
100 if ( !lockFile->isLocked() ) {
101 return true;
102 }
103
104 bool res = server->listen(socketName);
105 #if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))
106 // ### Workaround
107 if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {
108 QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
109 res = server->listen(socketName);
110 }
111 #endif
112 if (!res) {
113 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
114 }
115 QObject::connect( server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection );
116 return false;
117 }
118
119 bool QtLocalPeer::sendMessage(const QString &message, int timeout)
120 {
121 if (!isClient()) {
122 return false;
123 }
124
125 QLocalSocket socket;
126 bool connOk = false;
127 for(int i = 0; i < 2; i++) {
128 // Try twice, in case the other instance is just starting up
129 socket.connectToServer(socketName);
130 connOk = socket.waitForConnected(timeout/2);
131 if (connOk || i) {
132 break;
133 }
134 int ms = 250;
135 #if defined(Q_OS_WIN)
136 Sleep(DWORD(ms));
137 #else
138 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
139 nanosleep(&ts, NULL);
140 #endif
141 }
142 if (!connOk) {
143 return false;
144 }
145
146 QByteArray uMsg(message.toUtf8());
147 QDataStream ds(&socket);
148 ds.writeBytes(uMsg.constData(), uMsg.size());
149 bool res = socket.waitForBytesWritten(timeout);
150 if (res) {
151 res &= socket.waitForReadyRead(timeout); // wait for ack
152 if (res) {
153 res &= (socket.read(qstrlen(ack)) == ack);
154 }
155 }
156 return res;
157 }
158
159 void QtLocalPeer::receiveConnection()
160 {
161 QLocalSocket* socket = server->nextPendingConnection();
162 if (!socket) {
163 return;
164 }
165
166 while (socket->bytesAvailable() < (int)sizeof(quint32)) {
167 socket->waitForReadyRead();
168 }
169 QDataStream ds(socket);
170 QByteArray uMsg;
171 quint32 remaining;
172 ds >> remaining;
173 uMsg.resize(remaining);
174 int got = 0;
175 char* uMsgBuf = uMsg.data();
176 do {
177 got = ds.readRawData(uMsgBuf, remaining);
178 remaining -= got;
179 uMsgBuf += got;
180 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
181 if (got < 0) {
182 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
183 delete socket;
184 return;
185 }
186 QString message(QString::fromUtf8(uMsg));
187 socket->write(ack, qstrlen(ack));
188 socket->waitForBytesWritten(1000);
189 delete socket;
190 emit messageReceived(message); //### (might take a long time to return)
191 }
192
193 QtLocalPeer::~QtLocalPeer() {
194 server->close();
195 lockFile->unlock(); // Ensure file unlocked
196 }