| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "network-web/downloader.h" |
| 4 | |
| 5 | #include "miscellaneous/application.h" |
| 6 | #include "network-web/cookiejar.h" |
| 7 | #include "network-web/gemini/geminiparser.h" |
| 8 | #include "network-web/networkfactory.h" |
| 9 | #include "network-web/silentnetworkaccessmanager.h" |
| 10 | #include "network-web/webfactory.h" |
| 11 | |
| 12 | #include <QHttpMultiPart> |
| 13 | #include <QNetworkCookie> |
| 14 | #include <QRegularExpression> |
| 15 | #include <QTimer> |
| 16 | |
| 17 | Downloader::Downloader(QObject* parent) |
| 18 | : QObject(parent), m_geminiClient(new GeminiClient(this)), m_geminiParser(GeminiParser(false)), |
| 19 | m_activeReply(nullptr), m_downloadManager(new SilentNetworkAccessManager(this)), m_timer(new QTimer(this)), |
| 20 | m_inputData(QByteArray()), m_inputMultipartData(nullptr), m_targetProtected(false), m_targetUsername(QString()), |
| 21 | m_targetPassword(QString()), m_lastOutputData({}), m_lastOutputError(QNetworkReply::NetworkError::NoError), |
| 22 | m_lastHttpStatusCode(0), m_lastHeaders({}) { |
| 23 | m_timer->setInterval(DOWNLOAD_TIMEOUT); |
| 24 | m_timer->setSingleShot(true); |
| 25 | |
| 26 | connect(m_timer, &QTimer::timeout, this, &Downloader::cancel); |
| 27 | |
| 28 | connect(m_geminiClient, &GeminiClient::redirected, this, &Downloader::geminiRedirect); |
| 29 | connect(m_geminiClient, &GeminiClient::requestComplete, this, &Downloader::geminiFinished); |
| 30 | connect(m_geminiClient, &GeminiClient::networkError, this, &Downloader::geminiError); |
| 31 | |
| 32 | m_downloadManager->setCookieJar(qApp->web()->cookieJar()); |
| 33 | qApp->web()->cookieJar()->setParent(nullptr); |
| 34 | } |
| 35 | |
| 36 | Downloader::~Downloader() { |
| 37 | qDebugNN << LOGSEC_NETWORK << "Destroying Downloader instance."; |
| 38 | } |
| 39 | |
| 40 | void Downloader::geminiFinished(const QByteArray& data, const QString& mime) { |
| 41 | m_timer->stop(); |
| 42 | m_activeReply = nullptr; |
| 43 | |
| 44 | m_lastContentType = mime; |
| 45 | m_lastUrl = m_geminiClient->targetUrl(); |
| 46 | m_lastCookies = {}; |
| 47 | m_lastHeaders = {}; |
| 48 | m_lastHttpStatusCode = 0; |
| 49 | m_lastOutputError = QNetworkReply::NetworkError::NoError; |
| 50 | m_lastOutputMultipartData = {}; |
| 51 | |
| 52 | if (mime.startsWith(QSL(GEMINI_MIME_TYPE))) { |
| 53 | m_lastOutputData = m_geminiParser.geminiToHtml(data).toUtf8(); |
| 54 | } |
| 55 | else { |
| 56 | m_lastOutputData = data; |
| 57 | } |
| 58 | |
| 59 | emit completed(m_lastUrl, m_lastOutputError, m_lastHttpStatusCode, m_lastOutputData); |
| 60 | } |
| 61 | |
| 62 | void Downloader::geminiError(GeminiClient::NetworkError error, const QString& reason) { |
| 63 | m_timer->stop(); |
| 64 | m_activeReply = nullptr; |
| 65 | |
| 66 | m_lastContentType = QString(); |
| 67 | m_lastUrl = m_geminiClient->targetUrl(); |
| 68 | m_lastCookies = {}; |
| 69 | m_lastHeaders = {}; |
| 70 | m_lastHttpStatusCode = 404; |
| 71 | m_lastOutputData = QByteArray(); |
| 72 | m_lastOutputError = QNetworkReply::NetworkError::UnknownNetworkError; |
| 73 | m_lastOutputMultipartData = {}; |
| 74 | |
| 75 | emit completed(m_lastUrl, m_lastOutputError, m_lastHttpStatusCode); |
| 76 | } |
| 77 | |
| 78 | void Downloader::downloadFile(const QString& url, |
| 79 | int timeout, |
| 80 | bool protected_contents, |
| 81 | const QString& username, |
| 82 | const QString& password) { |
| 83 | manipulateData(url, |
| 84 | QNetworkAccessManager::GetOperation, |
| 85 | QByteArray(), |
| 86 | timeout, |
| 87 | protected_contents, |
| 88 | username, |
| 89 | password); |
| 90 | } |
| 91 | |
| 92 | void Downloader::uploadFile(const QString& url, |
| 93 | const QByteArray& data, |
| 94 | int timeout, |
| 95 | bool protected_contents, |
| 96 | const QString& username, |
| 97 | const QString& password) { |
| 98 | manipulateData(url, |
| 99 | QNetworkAccessManager::Operation::PostOperation, |
| 100 | data, |
| 101 | timeout, |
| 102 | protected_contents, |
| 103 | username, |
| 104 | password); |
| 105 | } |
| 106 | |
| 107 | void Downloader::manipulateData(const QString& url, |
| 108 | QNetworkAccessManager::Operation operation, |
| 109 | QHttpMultiPart* multipart_data, |
| 110 | int timeout, |
| 111 | bool protected_contents, |
| 112 | const QString& username, |
| 113 | const QString& password) { |
| 114 | manipulateData(url, operation, QByteArray(), multipart_data, timeout, protected_contents, username, password); |
| 115 | } |
| 116 | |
| 117 | void Downloader::manipulateData(const QString& url, |
| 118 | QNetworkAccessManager::Operation operation, |
| 119 | const QByteArray& data, |
| 120 | int timeout, |
| 121 | bool protected_contents, |
| 122 | const QString& username, |
| 123 | const QString& password) { |
| 124 | manipulateData(url, operation, data, nullptr, timeout, protected_contents, username, password); |
| 125 | } |
| 126 | |
| 127 | void Downloader::geminiRedirect(const QUrl& uri, bool is_permanent) { |
| 128 | m_timer->stop(); |
| 129 | |
| 130 | QUrl new_url = m_geminiClient->targetUrl().resolved(uri); |
| 131 | |
| 132 | runGeminiRequest(new_url); |
| 133 | } |
| 134 | |
| 135 | void Downloader::runGeminiRequest(const QUrl& url) { |
| 136 | m_timer->start(); |
| 137 | m_geminiClient->startRequest(url, GeminiClient::RequestOptions::IgnoreTlsErrors); |
| 138 | } |
| 139 | |
| 140 | void Downloader::manipulateData(const QString& url, |
| 141 | QNetworkAccessManager::Operation operation, |
| 142 | const QByteArray& data, |
| 143 | QHttpMultiPart* multipart_data, |
| 144 | int timeout, |
| 145 | bool protected_contents, |
| 146 | const QString& username, |
| 147 | const QString& password) { |
| 148 | QString sanitized_url = NetworkFactory::sanitizeUrl(url); |
| 149 | |
| 150 | if (m_geminiClient->supportsUrl(sanitized_url)) { |
| 151 | QUrl gemini_url = QUrl::fromUserInput(sanitized_url); |
| 152 | |
| 153 | runGeminiRequest(gemini_url); |
| 154 | } |
| 155 | else { |
| 156 | |
| 157 | auto cookies = CookieJar::extractCookiesFromUrl(sanitized_url); |
| 158 | |
| 159 | if (!cookies.isEmpty()) { |
| 160 | qApp->web()->cookieJar()->setCookiesFromUrl(cookies, sanitized_url); |
| 161 | } |
| 162 | |
| 163 | QNetworkRequest request; |
| 164 | QHashIterator<QByteArray, QByteArray> i(m_customHeaders); |
| 165 | |
| 166 | while (i.hasNext()) { |
| 167 | i.next(); |
| 168 | request.setRawHeader(i.key(), i.value()); |
| 169 | } |
| 170 | |
| 171 | m_inputData = data; |
| 172 | m_inputMultipartData = multipart_data; |
| 173 | |
| 174 | // Set url for this request and fire it up. |
| 175 | m_timer->setInterval(timeout); |
| 176 | |
| 177 | request.setUrl(qApp->web()->processFeedUriScheme(sanitized_url)); |
| 178 | |
| 179 | m_targetProtected = protected_contents; |
| 180 | m_targetUsername = username; |
| 181 | m_targetPassword = password; |
| 182 | |
| 183 | if (operation == QNetworkAccessManager::Operation::PostOperation) { |
| 184 | if (m_inputMultipartData == nullptr) { |
| 185 | runPostRequest(request, m_inputData); |
| 186 | } |
| 187 | else { |
| 188 | runPostRequest(request, m_inputMultipartData); |
| 189 | } |
| 190 | } |
| 191 | else if (operation == QNetworkAccessManager::GetOperation) { |
| 192 | runGetRequest(request); |
| 193 | } |
| 194 | else if (operation == QNetworkAccessManager::PutOperation) { |
| 195 | runPutRequest(request, m_inputData); |
| 196 | } |
| 197 | else if (operation == QNetworkAccessManager::DeleteOperation) { |
| 198 | runDeleteRequest(request); |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | static int numberOfRedirections(QNetworkReply* reply) { |
| 204 | return reply->property("redirections_count").toInt(); |
| 205 | } |
| 206 | |
| 207 | static int setNumberOfRedirections(QNetworkReply* reply, int number) { |
| 208 | return reply->setProperty("redirections_count", number); |
| 209 | } |
| 210 | |
| 211 | void Downloader::finished() { |
| 212 | auto* reply = qobject_cast<QNetworkReply*>(sender()); |
| 213 | |
| 214 | QNetworkAccessManager::Operation reply_operation = reply->operation(); |
| 215 | |
| 216 | m_timer->stop(); |
| 217 | |
| 218 | QUrl original_url = reply->property("original_url").toUrl(); |
| 219 | |
| 220 | if (!original_url.isValid()) { |
| 221 | original_url = reply->request().url(); |
| 222 | } |
| 223 | |
| 224 | // In this phase, some part of downloading process is completed. |
| 225 | QUrl redirection_url = reply->attribute(QNetworkRequest::Attribute::RedirectionTargetAttribute).toUrl(); |
| 226 | |
| 227 | if (redirection_url.isValid()) { |
| 228 | auto redir_number = numberOfRedirections(reply); |
| 229 | |
| 230 | qDebugNN << LOGSEC_NETWORK << "This network request was redirected" << QUOTE_W_SPACE(redir_number) << "times."; |
| 231 | |
| 232 | redir_number++; |
| 233 | |
| 234 | if (redir_number > MAX_NUMBER_OF_REDIRECTIONS) { |
| 235 | qDebugNN << LOGSEC_NETWORK << "Aborting request due too many redirections."; |
| 236 | |
| 237 | emit completed(redirection_url, QNetworkReply::NetworkError::TooManyRedirectsError, 404, {}); |
| 238 | return; |
| 239 | } |
| 240 | |
| 241 | // Communication indicates that HTTP redirection is needed. |
| 242 | // Setup redirection URL and download again. |
| 243 | QNetworkRequest request = reply->request(); |
| 244 | |
| 245 | qWarningNN << LOGSEC_NETWORK << "Network layer indicates HTTP redirection is needed."; |
| 246 | qWarningNN << LOGSEC_NETWORK << "Origin URL:" << QUOTE_W_SPACE_DOT(request.url().toString()); |
| 247 | qWarningNN << LOGSEC_NETWORK << "Proposed redirection URL:" << QUOTE_W_SPACE_DOT(redirection_url.toString()); |
| 248 | |
| 249 | redirection_url = request.url().resolved(redirection_url); |
| 250 | |
| 251 | qWarningNN << LOGSEC_NETWORK << "Resolved redirection URL:" << QUOTE_W_SPACE_DOT(redirection_url.toString()); |
| 252 | |
| 253 | request.setUrl(redirection_url); |
| 254 | |
| 255 | m_activeReply->deleteLater(); |
| 256 | m_activeReply = nullptr; |
| 257 | |
| 258 | if (reply_operation == QNetworkAccessManager::GetOperation) { |
| 259 | runGetRequest(request); |
| 260 | } |
| 261 | else if (reply_operation == QNetworkAccessManager::PostOperation) { |
| 262 | if (m_inputMultipartData == nullptr) { |
| 263 | runPostRequest(request, m_inputData); |
| 264 | } |
| 265 | else { |
| 266 | runPostRequest(request, m_inputMultipartData); |
| 267 | } |
| 268 | } |
| 269 | else if (reply_operation == QNetworkAccessManager::PutOperation) { |
| 270 | runPutRequest(request, m_inputData); |
| 271 | } |
| 272 | else if (reply_operation == QNetworkAccessManager::DeleteOperation) { |
| 273 | runDeleteRequest(request); |
| 274 | } |
| 275 | |
| 276 | if (m_activeReply != nullptr) { |
| 277 | m_activeReply->setProperty("original_url", original_url); |
| 278 | setNumberOfRedirections(m_activeReply, redir_number); |
| 279 | } |
| 280 | } |
| 281 | else { |
| 282 | // No redirection is indicated. Final file is obtained in our "reply" object. |
| 283 | // Read the data into output buffer. |
| 284 | if (m_inputMultipartData == nullptr) { |
| 285 | m_lastOutputData = reply->readAll(); |
| 286 | } |
| 287 | else { |
| 288 | m_lastOutputMultipartData = decodeMultipartAnswer(reply); |
| 289 | } |
| 290 | |
| 291 | QVariant set_cookies_header = reply->header(QNetworkRequest::SetCookieHeader); |
| 292 | |
| 293 | if (set_cookies_header.isValid()) { |
| 294 | QList<QNetworkCookie> cookies = set_cookies_header.value<QList<QNetworkCookie>>(); |
| 295 | |
| 296 | m_lastCookies = cookies; |
| 297 | } |
| 298 | else { |
| 299 | m_lastCookies = {}; |
| 300 | } |
| 301 | |
| 302 | m_lastUrl = reply->url(); |
| 303 | m_lastContentType = reply->header(QNetworkRequest::KnownHeaders::ContentTypeHeader).toString(); |
| 304 | m_lastOutputError = reply->error(); |
| 305 | m_lastHttpStatusCode = reply->attribute(QNetworkRequest::Attribute::HttpStatusCodeAttribute).toInt(); |
| 306 | m_lastHeaders.clear(); |
| 307 | |
| 308 | for (const QNetworkReply::RawHeaderPair& head : reply->rawHeaderPairs()) { |
| 309 | m_lastHeaders.insert(QString::fromLocal8Bit(head.first).toLower(), head.second); |
| 310 | } |
| 311 | |
| 312 | // original_url = m_activeReply->property("original_url").toUrl(); |
| 313 | |
| 314 | if (m_activeReply != nullptr) { |
| 315 | m_activeReply->deleteLater(); |
| 316 | m_activeReply = nullptr; |
| 317 | } |
| 318 | |
| 319 | if (m_inputMultipartData != nullptr) { |
| 320 | m_inputMultipartData->deleteLater(); |
| 321 | } |
| 322 | |
| 323 | emit completed(original_url, m_lastOutputError, m_lastHttpStatusCode, m_lastOutputData); |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | void Downloader::progressInternal(qint64 bytes_received, qint64 bytes_total) { |
| 328 | if (m_timer->interval() > 0) { |
| 329 | m_timer->start(); |
| 330 | } |
| 331 | |
| 332 | emit progress(bytes_received, bytes_total); |
| 333 | } |
| 334 | |
| 335 | void Downloader::setCustomPropsToReply(QNetworkReply* reply) { |
| 336 | reply->setProperty("protected", m_targetProtected); |
| 337 | reply->setProperty("username", m_targetUsername); |
| 338 | reply->setProperty("password", m_targetPassword); |
| 339 | } |
| 340 | |
| 341 | QList<HttpResponse> Downloader::decodeMultipartAnswer(QNetworkReply* reply) { |
| 342 | QByteArray data = reply->readAll(); |
| 343 | |
| 344 | if (data.isEmpty()) { |
| 345 | return QList<HttpResponse>(); |
| 346 | } |
| 347 | |
| 348 | QString content_type = reply->header(QNetworkRequest::KnownHeaders::ContentTypeHeader).toString(); |
| 349 | QString boundary = content_type.mid(content_type.indexOf(QL1S("boundary=")) + 9); |
| 350 | |
| 351 | QRegularExpression regex(QL1S("--") + boundary + QL1S("(--)?(\\r\\n)?")); |
| 352 | |
| 353 | QStringList list = QString::fromUtf8(data).split(regex, |
| 354 | #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 |
| 355 | Qt::SplitBehaviorFlags::SkipEmptyParts); |
| 356 | #else |
| 357 | QString::SplitBehavior::SkipEmptyParts); |
| 358 | #endif |
| 359 | |
| 360 | QList<HttpResponse> parts; |
| 361 | |
| 362 | parts.reserve(list.size()); |
| 363 | |
| 364 | for (const QString& http_response_str : list) { |
| 365 | // We separate headers and body. |
| 366 | HttpResponse new_part; |
| 367 | |
| 368 | static QRegularExpression reg_headers(QSL("\\r\\r?\\n")); |
| 369 | static QRegularExpression reg_body(QSL("(\\r\\r?\\n){2,}")); |
| 370 | static QRegularExpression reg_whites(QSL("[\\n\\r]+")); |
| 371 | |
| 372 | int start_of_http = http_response_str.indexOf(QL1S("HTTP/1.1")); |
| 373 | int start_of_headers = http_response_str.indexOf(reg_headers, start_of_http); |
| 374 | int start_of_body = http_response_str.indexOf(reg_body, start_of_headers + 2); |
| 375 | |
| 376 | QString body = http_response_str.mid(start_of_body); |
| 377 | QString headers = |
| 378 | http_response_str.mid(start_of_headers, start_of_body - start_of_headers).replace(reg_whites, QSL("\n")); |
| 379 | |
| 380 | auto header_lines = headers.split(QL1C('\n'), |
| 381 | #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0 |
| 382 | Qt::SplitBehaviorFlags::SkipEmptyParts); |
| 383 | #else |
| 384 | QString::SplitBehavior::SkipEmptyParts); |
| 385 | #endif |
| 386 | |
| 387 | for (const QString& header_line : std::as_const(header_lines)) { |
| 388 | int index_colon = header_line.indexOf(QL1C(':')); |
| 389 | |
| 390 | if (index_colon > 0) { |
| 391 | new_part.appendHeader(header_line.mid(0, index_colon), header_line.mid(index_colon + 2)); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | new_part.setBody(body); |
| 396 | parts.append(new_part); |
| 397 | } |
| 398 | |
| 399 | return parts; |
| 400 | } |
| 401 | |
| 402 | void Downloader::runDeleteRequest(const QNetworkRequest& request) { |
| 403 | m_timer->start(); |
| 404 | m_activeReply = m_downloadManager->deleteResource(request); |
| 405 | setCustomPropsToReply(m_activeReply); |
| 406 | connect(m_activeReply, &QNetworkReply::downloadProgress, this, &Downloader::progressInternal); |
| 407 | connect(m_activeReply, &QNetworkReply::finished, this, &Downloader::finished); |
| 408 | } |
| 409 | |
| 410 | void Downloader::runPutRequest(const QNetworkRequest& request, const QByteArray& data) { |
| 411 | m_timer->start(); |
| 412 | m_activeReply = m_downloadManager->put(request, data); |
| 413 | setCustomPropsToReply(m_activeReply); |
| 414 | connect(m_activeReply, &QNetworkReply::downloadProgress, this, &Downloader::progressInternal); |
| 415 | connect(m_activeReply, &QNetworkReply::finished, this, &Downloader::finished); |
| 416 | } |
| 417 | |
| 418 | void Downloader::runPostRequest(const QNetworkRequest& request, QHttpMultiPart* multipart_data) { |
| 419 | m_timer->start(); |
| 420 | m_activeReply = m_downloadManager->post(request, multipart_data); |
| 421 | setCustomPropsToReply(m_activeReply); |
| 422 | connect(m_activeReply, &QNetworkReply::downloadProgress, this, &Downloader::progressInternal); |
| 423 | connect(m_activeReply, &QNetworkReply::finished, this, &Downloader::finished); |
| 424 | } |
| 425 | |
| 426 | void Downloader::runPostRequest(const QNetworkRequest& request, const QByteArray& data) { |
| 427 | m_timer->start(); |
| 428 | m_activeReply = m_downloadManager->post(request, data); |
| 429 | setCustomPropsToReply(m_activeReply); |
| 430 | connect(m_activeReply, &QNetworkReply::downloadProgress, this, &Downloader::progressInternal); |
| 431 | connect(m_activeReply, &QNetworkReply::finished, this, &Downloader::finished); |
| 432 | } |
| 433 | |
| 434 | void Downloader::runGetRequest(const QNetworkRequest& request) { |
| 435 | m_timer->start(); |
| 436 | m_activeReply = m_downloadManager->get(request); |
| 437 | setCustomPropsToReply(m_activeReply); |
| 438 | connect(m_activeReply, &QNetworkReply::downloadProgress, this, &Downloader::progressInternal); |
| 439 | connect(m_activeReply, &QNetworkReply::finished, this, &Downloader::finished); |
| 440 | } |
| 441 | |
| 442 | QUrl Downloader::lastUrl() const { |
| 443 | return m_lastUrl; |
| 444 | } |
| 445 | |
| 446 | void Downloader::setHttp2Status(NetworkFactory::Http2Status status) { |
| 447 | m_downloadManager->setSpecificHtpp2Status(status); |
| 448 | } |
| 449 | |
| 450 | QMap<QString, QString> Downloader::lastHeaders() const { |
| 451 | return m_lastHeaders; |
| 452 | } |
| 453 | |
| 454 | int Downloader::lastHttpStatusCode() const { |
| 455 | return m_lastHttpStatusCode; |
| 456 | } |
| 457 | |
| 458 | QList<QNetworkCookie> Downloader::lastCookies() const { |
| 459 | return m_lastCookies; |
| 460 | } |
| 461 | |
| 462 | QString Downloader::lastContentType() const { |
| 463 | return m_lastContentType; |
| 464 | } |
| 465 | |
| 466 | void Downloader::setProxy(const QNetworkProxy& proxy) { |
| 467 | qWarningNN << LOGSEC_NETWORK << "Setting specific downloader proxy, address:" << QUOTE_W_SPACE_COMMA(proxy.hostName()) |
| 468 | << " type:" << QUOTE_W_SPACE_DOT(proxy.type()); |
| 469 | |
| 470 | m_downloadManager->setProxy(proxy); |
| 471 | } |
| 472 | |
| 473 | void Downloader::cancel() { |
| 474 | if (m_activeReply != nullptr) { |
| 475 | // Download action timed-out, too slow connection or target is not reachable. |
| 476 | m_activeReply->abort(); |
| 477 | } |
| 478 | else { |
| 479 | m_geminiClient->cancelRequest(); |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | void Downloader::appendRawHeaders(const QList<QPair<QByteArray, QByteArray>>& headers) { |
| 484 | for (const QPair<QByteArray, QByteArray>& header : headers) { |
| 485 | appendRawHeader(header.first, header.second); |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | void Downloader::appendRawHeader(const QByteArray& name, const QByteArray& value) { |
| 490 | if (!value.isEmpty()) { |
| 491 | m_customHeaders.insert(name, value); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | QNetworkReply::NetworkError Downloader::lastOutputError() const { |
| 496 | return m_lastOutputError; |
| 497 | } |
| 498 | |
| 499 | QList<HttpResponse> Downloader::lastOutputMultipartData() const { |
| 500 | return m_lastOutputMultipartData; |
| 501 | } |
| 502 | |
| 503 | QByteArray Downloader::lastOutputData() const { |
| 504 | return m_lastOutputData; |
| 505 | } |