Specify Unicode for resource block (#15370)
[qBittorrent.git] / src / app / qtlocalpeer / qtlocalpeer.cpp
blobb4b329abf5751c83d02d43fc7aa03ce8114b6a3b
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2019 Mike Tzou (Chocobo1)
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * In addition, as a special exception, the copyright holders give permission to
20 * link this program with the OpenSSL project's "OpenSSL" library (or with
21 * modified versions of it that use the same license as the "OpenSSL" library),
22 * and distribute the linked executables. You must obey the GNU General Public
23 * License in all respects for all of the code used other than "OpenSSL". If you
24 * modify file(s), you may extend this exception to your version of the file(s),
25 * but you are not obligated to do so. If you do not wish to do so, delete this
26 * exception statement from your version.
28 ****************************************************************************
30 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
31 ** Contact: http://www.qt-project.org/legal
33 ** This file is part of the Qt Solutions component.
35 ** $QT_BEGIN_LICENSE:BSD$
36 ** You may use this file under the terms of the BSD license as follows:
38 ** "Redistribution and use in source and binary forms, with or without
39 ** modification, are permitted provided that the following conditions are
40 ** met:
41 ** * Redistributions of source code must retain the above copyright
42 ** notice, this list of conditions and the following disclaimer.
43 ** * Redistributions in binary form must reproduce the above copyright
44 ** notice, this list of conditions and the following disclaimer in
45 ** the documentation and/or other materials provided with the
46 ** distribution.
47 ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
48 ** of its contributors may be used to endorse or promote products derived
49 ** from this software without specific prior written permission.
52 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
53 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
54 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
55 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
56 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
58 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
59 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
60 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
61 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
62 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
64 ** $QT_END_LICENSE$
66 ****************************************************************************
69 #include "qtlocalpeer.h"
71 #if defined(Q_OS_UNIX)
72 #include <sys/types.h>
73 #include <time.h>
74 #include <unistd.h>
75 #endif
77 #include <QCoreApplication>
78 #include <QDataStream>
79 #include <QDir>
80 #include <QLocalServer>
81 #include <QLocalSocket>
82 #include <QRegularExpression>
84 #include "base/utils/misc.h"
86 namespace QtLP_Private
88 #include "qtlockedfile.cpp"
90 #if defined(Q_OS_WIN)
91 #include "qtlockedfile_win.cpp"
92 #else
93 #include "qtlockedfile_unix.cpp"
94 #endif
97 const char* QtLocalPeer::ack = "ack";
99 QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
100 : QObject(parent)
101 , id(appId)
103 QString prefix = id;
104 if (id.isEmpty())
106 id = QCoreApplication::applicationFilePath();
107 #if defined(Q_OS_WIN)
108 id = id.toLower();
109 #endif
110 prefix = id.section(QLatin1Char('/'), -1);
112 prefix.remove(QRegularExpression("[^a-zA-Z]"));
113 prefix.truncate(6);
115 QByteArray idc = id.toUtf8();
116 quint16 idNum = qChecksum(idc.constData(), idc.size());
117 socketName = QLatin1String("qtsingleapp-") + prefix
118 + QLatin1Char('-') + QString::number(idNum, 16);
120 #if defined(Q_OS_WIN)
121 DWORD sessionId = 0;
122 ::ProcessIdToSessionId(GetCurrentProcessId(), &sessionId);
123 socketName += (QLatin1Char('-') + QString::number(sessionId, 16));
124 #else
125 socketName += (QLatin1Char('-') + QString::number(::getuid(), 16));
126 #endif
128 server = new QLocalServer(this);
129 server->setSocketOptions(QLocalServer::UserAccessOption);
130 QString lockName = QDir(QDir::tempPath()).absolutePath()
131 + QLatin1Char('/') + socketName
132 + QLatin1String("-lockfile");
133 lockFile.setFileName(lockName);
134 lockFile.open(QIODevice::ReadWrite);
137 QtLocalPeer::~QtLocalPeer()
139 if (!isClient())
141 lockFile.unlock();
142 lockFile.remove();
146 bool QtLocalPeer::isClient()
148 if (lockFile.isLocked())
149 return false;
151 if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
152 return true;
154 bool res = server->listen(socketName);
155 #if defined(Q_OS_UNIX)
156 // ### Workaround
157 if (!res && server->serverError() == QAbstractSocket::AddressInUseError)
159 QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);
160 res = server->listen(socketName);
162 #endif
163 if (!res)
164 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qPrintable(server->errorString()));
165 connect(server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection);
166 return false;
169 bool QtLocalPeer::sendMessage(const QString &message, const int timeout)
171 if (!isClient())
172 return false;
174 QLocalSocket socket;
175 bool connOk = false;
176 for(int i = 0; i < 2; i++)
178 // Try twice, in case the other instance is just starting up
179 socket.connectToServer(socketName);
180 connOk = socket.waitForConnected(timeout/2);
181 if (connOk || i)
182 break;
183 int ms = 250;
184 #if defined(Q_OS_WIN)
185 Sleep(DWORD(ms));
186 #else
187 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
188 nanosleep(&ts, NULL);
189 #endif
191 if (!connOk)
192 return false;
194 QByteArray uMsg(message.toUtf8());
195 QDataStream ds(&socket);
196 ds.writeBytes(uMsg.constData(), uMsg.size());
197 bool res = socket.waitForBytesWritten(timeout);
198 if (res)
200 res &= socket.waitForReadyRead(timeout); // wait for ack
201 if (res)
202 res &= (socket.read(qstrlen(ack)) == ack);
204 return res;
207 QString QtLocalPeer::applicationId() const
209 return id;
212 void QtLocalPeer::receiveConnection()
214 QLocalSocket* socket = server->nextPendingConnection();
215 if (!socket)
216 return;
218 while (true)
220 if (socket->state() == QLocalSocket::UnconnectedState)
222 qWarning("QtLocalPeer: Peer disconnected");
223 delete socket;
224 return;
226 if (socket->bytesAvailable() >= qint64(sizeof(quint32)))
227 break;
228 socket->waitForReadyRead();
231 QDataStream ds(socket);
232 QByteArray uMsg;
233 quint32 remaining;
234 ds >> remaining;
235 if (remaining > 65535)
237 // drop suspiciously large data
238 delete socket;
239 return;
242 uMsg.resize(remaining);
243 int got = 0;
244 char* uMsgBuf = uMsg.data();
247 got = ds.readRawData(uMsgBuf, remaining);
248 remaining -= got;
249 uMsgBuf += got;
250 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
251 if (got < 0)
253 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
254 delete socket;
255 return;
257 QString message(QString::fromUtf8(uMsg));
258 socket->write(ack, qstrlen(ack));
259 socket->waitForBytesWritten(1000);
260 socket->waitForDisconnected(1000); // make sure client reads ack
261 delete socket;
262 emit messageReceived(message); //### (might take a long time to return)