WebAPI: add new method setTags to upsert tags on torrents
[qBittorrent.git] / src / app / qtlocalpeer / qtlocalpeer.cpp
blobcc97eb4642c2562a1623846abbbc4d81e5069d64
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 #include <QtSystemDetection>
73 #if defined(Q_OS_WIN)
74 #include <windows.h>
75 #endif
77 #include <QByteArray>
78 #include <QDataStream>
79 #include <QFileInfo>
80 #include <QLocalServer>
81 #include <QLocalSocket>
83 namespace QtLP_Private
85 #include "qtlockedfile.cpp"
87 #if defined(Q_OS_WIN)
88 #include "qtlockedfile_win.cpp"
89 #else
90 #include "qtlockedfile_unix.cpp"
91 #endif
94 const QByteArray ACK = QByteArrayLiteral("ack");
96 QtLocalPeer::QtLocalPeer(const QString &path, QObject *parent)
97 : QObject(parent)
98 , m_socketName(path + u"/ipc-socket")
99 , m_server(new QLocalServer(this))
101 m_server->setSocketOptions(QLocalServer::UserAccessOption);
103 m_lockFile.setFileName(path + u"/lockfile");
104 m_lockFile.open(QIODevice::ReadWrite);
107 QtLocalPeer::~QtLocalPeer()
109 if (!isClient())
111 m_lockFile.unlock();
112 m_lockFile.remove();
116 bool QtLocalPeer::isClient()
118 if (m_lockFile.isLocked())
119 return false;
121 if (!m_lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))
122 return true;
124 bool res = m_server->listen(m_socketName);
125 #if defined(Q_OS_UNIX)
126 // ### Workaround
127 if (!res && m_server->serverError() == QAbstractSocket::AddressInUseError)
129 QFile::remove(m_socketName);
130 res = m_server->listen(m_socketName);
132 #endif
133 if (!res)
134 qWarning("QtSingleCoreApplication: listen on local socket failed, %s", qUtf8Printable(m_server->errorString()));
136 connect(m_server, &QLocalServer::newConnection, this, &QtLocalPeer::receiveConnection);
137 return false;
140 bool QtLocalPeer::sendMessage(const QString &message, const int timeout)
142 if (!isClient())
143 return false;
145 QLocalSocket socket;
146 bool connOk = false;
147 for(int i = 0; i < 2; i++)
149 // Try twice, in case the other instance is just starting up
150 socket.connectToServer(m_socketName);
151 connOk = socket.waitForConnected(timeout/2);
152 if (connOk || i)
153 break;
154 int ms = 250;
155 #if defined(Q_OS_WIN)
156 ::Sleep(DWORD(ms));
157 #else
158 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
159 ::nanosleep(&ts, nullptr);
160 #endif
162 if (!connOk)
163 return false;
165 QByteArray uMsg(message.toUtf8());
166 QDataStream ds(&socket);
167 ds.writeBytes(uMsg.constData(), uMsg.size());
168 bool res = socket.waitForBytesWritten(timeout);
169 if (res)
171 res &= socket.waitForReadyRead(timeout); // wait for ack
172 if (res)
173 res &= (socket.read(ACK.size()) == ACK);
175 return res;
178 void QtLocalPeer::receiveConnection()
180 QLocalSocket *socket = m_server->nextPendingConnection();
181 if (!socket)
182 return;
184 while (true)
186 if (socket->state() == QLocalSocket::UnconnectedState)
188 qWarning("QtLocalPeer: Peer disconnected");
189 delete socket;
190 return;
192 if (socket->bytesAvailable() >= qint64(sizeof(quint32)))
193 break;
194 socket->waitForReadyRead();
197 QDataStream ds(socket);
198 QByteArray uMsg;
199 quint32 remaining;
200 ds >> remaining;
201 if (remaining > 65535)
203 // drop suspiciously large data
204 delete socket;
205 return;
208 uMsg.resize(remaining);
209 int got = 0;
210 char* uMsgBuf = uMsg.data();
213 got = ds.readRawData(uMsgBuf, remaining);
214 remaining -= got;
215 uMsgBuf += got;
216 } while (remaining && got >= 0 && socket->waitForReadyRead(2000));
217 if (got < 0)
219 qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
220 delete socket;
221 return;
223 QString message(QString::fromUtf8(uMsg));
224 socket->write(ACK);
225 socket->waitForBytesWritten(1000);
226 socket->waitForDisconnected(1000); // make sure client reads ack
227 delete socket;
228 emit messageReceived(message); //### (might take a long time to return)