Allow to globally disable the use of proxy
[qBittorrent.git] / src / base / net / downloadhandlerimpl.cpp
blob58648714bd8d1b6a3f58affc52cb337887f2eb2f
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015, 2018 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include "downloadhandlerimpl.h"
32 #include <QTemporaryFile>
33 #include <QUrl>
35 #include "base/3rdparty/expected.hpp"
36 #include "base/utils/fs.h"
37 #include "base/utils/io.h"
38 #include "base/utils/misc.h"
40 #ifdef QT_NO_COMPRESS
41 #include "base/utils/gzip.h"
42 #endif
44 const int MAX_REDIRECTIONS = 20; // the common value for web browsers
46 namespace
48 nonstd::expected<Path, QString> saveToTempFile(const QByteArray &data)
50 QTemporaryFile file {Utils::Fs::tempPath().data()};
51 if (!file.open() || (file.write(data) != data.length()) || !file.flush())
52 return nonstd::make_unexpected(file.errorString());
54 file.setAutoRemove(false);
55 return Path(file.fileName());
59 Net::DownloadHandlerImpl::DownloadHandlerImpl(DownloadManager *manager
60 , const DownloadRequest &downloadRequest, const bool useProxy)
61 : DownloadHandler {manager}
62 , m_manager {manager}
63 , m_downloadRequest {downloadRequest}
64 , m_useProxy {useProxy}
66 m_result.url = url();
67 m_result.status = DownloadStatus::Success;
70 void Net::DownloadHandlerImpl::cancel()
72 if (m_reply)
74 m_reply->abort();
76 else
78 setError(errorCodeToString(QNetworkReply::OperationCanceledError));
79 finish();
83 void Net::DownloadHandlerImpl::assignNetworkReply(QNetworkReply *reply)
85 Q_ASSERT(reply);
86 Q_ASSERT(!m_reply);
88 m_reply = reply;
89 m_reply->setParent(this);
90 if (m_downloadRequest.limit() > 0)
91 connect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadHandlerImpl::checkDownloadSize);
92 connect(m_reply, &QNetworkReply::finished, this, &DownloadHandlerImpl::processFinishedDownload);
95 // Returns original url
96 QString Net::DownloadHandlerImpl::url() const
98 return m_downloadRequest.url();
101 Net::DownloadRequest Net::DownloadHandlerImpl::downloadRequest() const
103 return m_downloadRequest;
106 bool Net::DownloadHandlerImpl::useProxy() const
108 return m_useProxy;
111 void Net::DownloadHandlerImpl::processFinishedDownload()
113 qDebug("Download finished: %s", qUtf8Printable(url()));
115 // Check if the request was successful
116 if (m_reply->error() != QNetworkReply::NoError)
118 // Failure
119 qDebug("Download failure (%s), reason: %s", qUtf8Printable(url()), qUtf8Printable(errorCodeToString(m_reply->error())));
120 setError(errorCodeToString(m_reply->error()));
121 finish();
122 return;
125 // Check if the server ask us to redirect somewhere else
126 const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
127 if (redirection.isValid())
129 handleRedirection(redirection.toUrl());
130 return;
133 // Success
134 #ifdef QT_NO_COMPRESS
135 m_result.data = (m_reply->rawHeader("Content-Encoding") == "gzip")
136 ? Utils::Gzip::decompress(m_reply->readAll())
137 : m_reply->readAll();
138 #else
139 m_result.data = m_reply->readAll();
140 #endif
142 if (m_downloadRequest.saveToFile())
144 const Path destinationPath = m_downloadRequest.destFileName();
145 if (destinationPath.isEmpty())
147 const nonstd::expected<Path, QString> result = saveToTempFile(m_result.data);
148 if (result)
149 m_result.filePath = result.value();
150 else
151 setError(tr("I/O Error: %1").arg(result.error()));
153 else
155 const nonstd::expected<void, QString> result = Utils::IO::saveToFile(destinationPath, m_result.data);
156 if (result)
157 m_result.filePath = destinationPath;
158 else
159 setError(tr("I/O Error: %1").arg(result.error()));
163 finish();
166 void Net::DownloadHandlerImpl::checkDownloadSize(const qint64 bytesReceived, const qint64 bytesTotal)
168 if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit()))
170 // Total number of bytes is available
171 disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadHandlerImpl::checkDownloadSize);
172 return;
175 if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit()))
177 m_reply->abort();
178 setError(tr("The file size (%1) exceeds the download limit (%2)")
179 .arg(Utils::Misc::friendlyUnit(bytesTotal)
180 , Utils::Misc::friendlyUnit(m_downloadRequest.limit())));
181 finish();
185 void Net::DownloadHandlerImpl::handleRedirection(const QUrl &newUrl)
187 if (m_redirectionCount >= MAX_REDIRECTIONS)
189 setError(tr("Exceeded max redirections (%1)").arg(MAX_REDIRECTIONS));
190 finish();
191 return;
194 // Resolve relative urls
195 const QUrl resolvedUrl = newUrl.isRelative() ? m_reply->url().resolved(newUrl) : newUrl;
196 const QString newUrlString = resolvedUrl.toString();
197 qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString));
199 // Redirect to magnet workaround
200 if (newUrlString.startsWith(u"magnet:", Qt::CaseInsensitive))
202 qDebug("Magnet redirect detected.");
203 m_result.status = Net::DownloadStatus::RedirectedToMagnet;
204 m_result.magnet = newUrlString;
205 m_result.errorString = tr("Redirected to magnet URI");
207 finish();
208 return;
211 auto *redirected = static_cast<DownloadHandlerImpl *>(
212 m_manager->download(DownloadRequest(m_downloadRequest).url(newUrlString), useProxy()));
213 redirected->m_redirectionCount = m_redirectionCount + 1;
214 connect(redirected, &DownloadHandlerImpl::finished, this, [this](const DownloadResult &result)
216 m_result = result;
217 m_result.url = url();
218 finish();
222 void Net::DownloadHandlerImpl::setError(const QString &error)
224 m_result.errorString = error;
225 m_result.status = DownloadStatus::Failed;
228 void Net::DownloadHandlerImpl::finish()
230 emit finished(m_result);
233 QString Net::DownloadHandlerImpl::errorCodeToString(const QNetworkReply::NetworkError status)
235 switch (status)
237 case QNetworkReply::HostNotFoundError:
238 return tr("The remote host name was not found (invalid hostname)");
239 case QNetworkReply::OperationCanceledError:
240 return tr("The operation was canceled");
241 case QNetworkReply::RemoteHostClosedError:
242 return tr("The remote server closed the connection prematurely, before the entire reply was received and processed");
243 case QNetworkReply::TimeoutError:
244 return tr("The connection to the remote server timed out");
245 case QNetworkReply::SslHandshakeFailedError:
246 return tr("SSL/TLS handshake failed");
247 case QNetworkReply::ConnectionRefusedError:
248 return tr("The remote server refused the connection");
249 case QNetworkReply::ProxyConnectionRefusedError:
250 return tr("The connection to the proxy server was refused");
251 case QNetworkReply::ProxyConnectionClosedError:
252 return tr("The proxy server closed the connection prematurely");
253 case QNetworkReply::ProxyNotFoundError:
254 return tr("The proxy host name was not found");
255 case QNetworkReply::ProxyTimeoutError:
256 return tr("The connection to the proxy timed out or the proxy did not reply in time to the request sent");
257 case QNetworkReply::ProxyAuthenticationRequiredError:
258 return tr("The proxy requires authentication in order to honor the request but did not accept any credentials offered");
259 case QNetworkReply::ContentAccessDenied:
260 return tr("The access to the remote content was denied (401)");
261 case QNetworkReply::ContentOperationNotPermittedError:
262 return tr("The operation requested on the remote content is not permitted");
263 case QNetworkReply::ContentNotFoundError:
264 return tr("The remote content was not found at the server (404)");
265 case QNetworkReply::AuthenticationRequiredError:
266 return tr("The remote server requires authentication to serve the content but the credentials provided were not accepted");
267 case QNetworkReply::ProtocolUnknownError:
268 return tr("The Network Access API cannot honor the request because the protocol is not known");
269 case QNetworkReply::ProtocolInvalidOperationError:
270 return tr("The requested operation is invalid for this protocol");
271 case QNetworkReply::UnknownNetworkError:
272 return tr("An unknown network-related error was detected");
273 case QNetworkReply::UnknownProxyError:
274 return tr("An unknown proxy-related error was detected");
275 case QNetworkReply::UnknownContentError:
276 return tr("An unknown error related to the remote content was detected");
277 case QNetworkReply::ProtocolFailure:
278 return tr("A breakdown in protocol was detected");
279 default:
280 return tr("Unknown error");