Fine tune translations loading for Chinese locales
[qBittorrent.git] / src / webui / webapplication.cpp
blobd35a48c878bc2564c08a068ef3c00dc18293956a
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2014, 2022 Vladimir Golovnev <glassez@yandex.ru>
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.
29 #include "webapplication.h"
31 #include <algorithm>
33 #include <QDateTime>
34 #include <QDebug>
35 #include <QFile>
36 #include <QFileInfo>
37 #include <QJsonDocument>
38 #include <QMimeDatabase>
39 #include <QMimeType>
40 #include <QNetworkCookie>
41 #include <QRegularExpression>
42 #include <QUrl>
44 #include "base/algorithm.h"
45 #include "base/http/httperror.h"
46 #include "base/logger.h"
47 #include "base/preferences.h"
48 #include "base/types.h"
49 #include "base/utils/bytearray.h"
50 #include "base/utils/fs.h"
51 #include "base/utils/misc.h"
52 #include "base/utils/random.h"
53 #include "base/utils/string.h"
54 #include "api/apierror.h"
55 #include "api/appcontroller.h"
56 #include "api/authcontroller.h"
57 #include "api/logcontroller.h"
58 #include "api/rsscontroller.h"
59 #include "api/searchcontroller.h"
60 #include "api/synccontroller.h"
61 #include "api/torrentscontroller.h"
62 #include "api/transfercontroller.h"
64 const int MAX_ALLOWED_FILESIZE = 10 * 1024 * 1024;
65 const auto C_SID = QByteArrayLiteral("SID"); // name of session id cookie
67 const QString WWW_FOLDER = u":/www"_qs;
68 const QString PUBLIC_FOLDER = u"/public"_qs;
69 const QString PRIVATE_FOLDER = u"/private"_qs;
71 namespace
73 QStringMap parseCookie(const QStringView cookieStr)
75 // [rfc6265] 4.2.1. Syntax
76 QStringMap ret;
77 const QList<QStringView> cookies = cookieStr.split(u';', Qt::SkipEmptyParts);
79 for (const auto &cookie : cookies)
81 const int idx = cookie.indexOf(u'=');
82 if (idx < 0)
83 continue;
85 const QString name = cookie.left(idx).trimmed().toString();
86 const QString value = Utils::String::unquote(cookie.mid(idx + 1).trimmed()).toString();
87 ret.insert(name, value);
89 return ret;
92 QUrl urlFromHostHeader(const QString &hostHeader)
94 if (!hostHeader.contains(u"://"))
95 return {u"http://"_qs + hostHeader};
96 return hostHeader;
99 QString getCachingInterval(QString contentType)
101 contentType = contentType.toLower();
103 if (contentType.startsWith(u"image/"))
104 return u"private, max-age=604800"_qs; // 1 week
106 if ((contentType == Http::CONTENT_TYPE_CSS)
107 || (contentType == Http::CONTENT_TYPE_JS))
109 // short interval in case of program update
110 return u"private, max-age=43200"_qs; // 12 hrs
113 return u"no-store"_qs;
117 WebApplication::WebApplication(IApplication *app, QObject *parent)
118 : QObject(parent)
119 , ApplicationComponent(app)
120 , m_cacheID {QString::number(Utils::Random::rand(), 36)}
121 , m_authController {new AuthController(this, app, this)}
123 declarePublicAPI(u"auth/login"_qs);
125 configure();
126 connect(Preferences::instance(), &Preferences::changed, this, &WebApplication::configure);
129 WebApplication::~WebApplication()
131 // cleanup sessions data
132 qDeleteAll(m_sessions);
135 void WebApplication::sendWebUIFile()
137 const QStringList pathItems {request().path.split(u'/', Qt::SkipEmptyParts)};
138 if (pathItems.contains(u".") || pathItems.contains(u".."))
139 throw InternalServerErrorHTTPError();
141 const QString path = (request().path != u"/")
142 ? request().path
143 : u"/index.html"_qs;
145 Path localPath = m_rootFolder
146 / Path(session() ? PRIVATE_FOLDER : PUBLIC_FOLDER)
147 / Path(path);
148 if (!localPath.exists() && session())
150 // try to send public file if there is no private one
151 localPath = m_rootFolder / Path(PUBLIC_FOLDER) / Path(path);
154 if (m_isAltUIUsed)
156 if (!Utils::Fs::isRegularFile(localPath))
157 throw InternalServerErrorHTTPError(tr("Unacceptable file type, only regular file is allowed."));
159 const QString rootFolder = m_rootFolder.data();
161 QFileInfo fileInfo {localPath.parentPath().data()};
162 while (fileInfo.path() != rootFolder)
164 if (fileInfo.isSymLink())
165 throw InternalServerErrorHTTPError(tr("Symlinks inside alternative UI folder are forbidden."));
167 fileInfo.setFile(fileInfo.path());
171 sendFile(localPath);
174 void WebApplication::translateDocument(QString &data) const
176 const QRegularExpression regex(u"QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\]"_qs);
178 int i = 0;
179 bool found = true;
180 while (i < data.size() && found)
182 QRegularExpressionMatch regexMatch;
183 i = data.indexOf(regex, i, &regexMatch);
184 if (i >= 0)
186 const QString sourceText = regexMatch.captured(1);
187 const QString context = regexMatch.captured(3);
189 const QString loadedText = m_translationFileLoaded
190 ? m_translator.translate(context.toUtf8().constData(), sourceText.toUtf8().constData())
191 : QString();
192 // `loadedText` is empty when translation is not provided
193 // it should fallback to `sourceText`
194 QString translation = loadedText.isEmpty() ? sourceText : loadedText;
196 // Use HTML code for quotes to prevent issues with JS
197 translation.replace(u'\'', u"&#39;"_qs);
198 translation.replace(u'\"', u"&#34;"_qs);
200 data.replace(i, regexMatch.capturedLength(), translation);
201 i += translation.length();
203 else
205 found = false; // no more translatable strings
208 data.replace(u"${LANG}"_qs, m_currentLocale.left(2));
209 data.replace(u"${CACHEID}"_qs, m_cacheID);
213 WebSession *WebApplication::session()
215 return m_currentSession;
218 const Http::Request &WebApplication::request() const
220 return m_request;
223 const Http::Environment &WebApplication::env() const
225 return m_env;
228 void WebApplication::doProcessRequest()
230 const QRegularExpressionMatch match = m_apiPathPattern.match(request().path);
231 if (!match.hasMatch())
233 sendWebUIFile();
234 return;
237 const QString action = match.captured(u"action"_qs);
238 const QString scope = match.captured(u"scope"_qs);
240 // Check public/private scope
241 if (!session() && !isPublicAPI(scope, action))
242 throw ForbiddenHTTPError();
244 // Find matching API
245 APIController *controller = nullptr;
246 if (session())
247 controller = session()->getAPIController(scope);
248 if (!controller)
250 if (scope == u"auth")
251 controller = m_authController;
252 else
253 throw NotFoundHTTPError();
256 // Filter HTTP methods
257 const auto allowedMethodIter = m_allowedMethod.find({scope, action});
258 if (allowedMethodIter == m_allowedMethod.end())
260 // by default allow both GET, POST methods
261 if ((m_request.method != Http::METHOD_GET) && (m_request.method != Http::METHOD_POST))
262 throw MethodNotAllowedHTTPError();
264 else
266 if (*allowedMethodIter != m_request.method)
267 throw MethodNotAllowedHTTPError();
270 DataMap data;
271 for (const Http::UploadedFile &torrent : request().files)
272 data[torrent.filename] = torrent.data;
276 const QVariant result = controller->run(action, m_params, data);
277 switch (result.userType())
279 case QMetaType::QJsonDocument:
280 print(result.toJsonDocument().toJson(QJsonDocument::Compact), Http::CONTENT_TYPE_JSON);
281 break;
282 case QMetaType::QByteArray:
283 print(result.toByteArray(), Http::CONTENT_TYPE_TXT);
284 break;
285 case QMetaType::QString:
286 default:
287 print(result.toString(), Http::CONTENT_TYPE_TXT);
288 break;
291 catch (const APIError &error)
293 // re-throw as HTTPError
294 switch (error.type())
296 case APIErrorType::AccessDenied:
297 throw ForbiddenHTTPError(error.message());
298 case APIErrorType::BadData:
299 throw UnsupportedMediaTypeHTTPError(error.message());
300 case APIErrorType::BadParams:
301 throw BadRequestHTTPError(error.message());
302 case APIErrorType::Conflict:
303 throw ConflictHTTPError(error.message());
304 case APIErrorType::NotFound:
305 throw NotFoundHTTPError(error.message());
306 default:
307 Q_ASSERT(false);
312 void WebApplication::configure()
314 const auto *pref = Preferences::instance();
316 const bool isAltUIUsed = pref->isAltWebUiEnabled();
317 const Path rootFolder = (!isAltUIUsed ? Path(WWW_FOLDER) : pref->getWebUiRootFolder());
318 if ((isAltUIUsed != m_isAltUIUsed) || (rootFolder != m_rootFolder))
320 m_isAltUIUsed = isAltUIUsed;
321 m_rootFolder = rootFolder;
322 m_translatedFiles.clear();
323 if (!m_isAltUIUsed)
324 LogMsg(tr("Using built-in Web UI."));
325 else
326 LogMsg(tr("Using custom Web UI. Location: \"%1\".").arg(m_rootFolder.toString()));
329 const QString newLocale = pref->getLocale();
330 if (m_currentLocale != newLocale)
332 m_currentLocale = newLocale;
333 m_translatedFiles.clear();
335 m_translationFileLoaded = m_translator.load((m_rootFolder / Path(u"translations/webui_"_qs) + newLocale).data());
336 if (m_translationFileLoaded)
338 LogMsg(tr("Web UI translation for selected locale (%1) has been successfully loaded.")
339 .arg(newLocale));
341 else
343 LogMsg(tr("Couldn't load Web UI translation for selected locale (%1).").arg(newLocale), Log::WARNING);
347 m_isLocalAuthEnabled = pref->isWebUiLocalAuthEnabled();
348 m_isAuthSubnetWhitelistEnabled = pref->isWebUiAuthSubnetWhitelistEnabled();
349 m_authSubnetWhitelist = pref->getWebUiAuthSubnetWhitelist();
350 m_sessionTimeout = pref->getWebUISessionTimeout();
352 m_domainList = pref->getServerDomains().split(u';', Qt::SkipEmptyParts);
353 std::for_each(m_domainList.begin(), m_domainList.end(), [](QString &entry) { entry = entry.trimmed(); });
355 m_isCSRFProtectionEnabled = pref->isWebUiCSRFProtectionEnabled();
356 m_isSecureCookieEnabled = pref->isWebUiSecureCookieEnabled();
357 m_isHostHeaderValidationEnabled = pref->isWebUIHostHeaderValidationEnabled();
358 m_isHttpsEnabled = pref->isWebUiHttpsEnabled();
360 m_prebuiltHeaders.clear();
361 m_prebuiltHeaders.push_back({Http::HEADER_X_XSS_PROTECTION, u"1; mode=block"_qs});
362 m_prebuiltHeaders.push_back({Http::HEADER_X_CONTENT_TYPE_OPTIONS, u"nosniff"_qs});
364 if (!m_isAltUIUsed)
365 m_prebuiltHeaders.push_back({Http::HEADER_REFERRER_POLICY, u"same-origin"_qs});
367 const bool isClickjackingProtectionEnabled = pref->isWebUiClickjackingProtectionEnabled();
368 if (isClickjackingProtectionEnabled)
369 m_prebuiltHeaders.push_back({Http::HEADER_X_FRAME_OPTIONS, u"SAMEORIGIN"_qs});
371 const QString contentSecurityPolicy =
372 (m_isAltUIUsed
373 ? QString()
374 : u"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self';"_qs)
375 + (isClickjackingProtectionEnabled ? u" frame-ancestors 'self';"_qs : QString())
376 + (m_isHttpsEnabled ? u" upgrade-insecure-requests;"_qs : QString());
377 if (!contentSecurityPolicy.isEmpty())
378 m_prebuiltHeaders.push_back({Http::HEADER_CONTENT_SECURITY_POLICY, contentSecurityPolicy});
380 if (pref->isWebUICustomHTTPHeadersEnabled())
382 const QString customHeaders = pref->getWebUICustomHTTPHeaders();
383 const QList<QStringView> customHeaderLines = QStringView(customHeaders).trimmed().split(u'\n', Qt::SkipEmptyParts);
385 for (const QStringView line : customHeaderLines)
387 const int idx = line.indexOf(u':');
388 if (idx < 0)
390 // require separator `:` to be present even if `value` field can be empty
391 LogMsg(tr("Missing ':' separator in WebUI custom HTTP header: \"%1\"").arg(line.toString()), Log::WARNING);
392 continue;
395 const QString header = line.left(idx).trimmed().toString();
396 const QString value = line.mid(idx + 1).trimmed().toString();
397 m_prebuiltHeaders.push_back({header, value});
401 m_isReverseProxySupportEnabled = pref->isWebUIReverseProxySupportEnabled();
402 if (m_isReverseProxySupportEnabled)
404 const QStringList proxyList = pref->getWebUITrustedReverseProxiesList().split(u';', Qt::SkipEmptyParts);
406 m_trustedReverseProxyList.clear();
407 m_trustedReverseProxyList.reserve(proxyList.size());
409 for (QString proxy : proxyList)
411 if (!proxy.contains(u'/'))
413 const QAbstractSocket::NetworkLayerProtocol protocol = QHostAddress(proxy).protocol();
414 if (protocol == QAbstractSocket::IPv4Protocol)
416 proxy.append(u"/32");
418 else if (protocol == QAbstractSocket::IPv6Protocol)
420 proxy.append(u"/128");
424 const std::optional<Utils::Net::Subnet> subnet = Utils::Net::parseSubnet(proxy);
425 if (subnet)
426 m_trustedReverseProxyList.push_back(subnet.value());
429 if (m_trustedReverseProxyList.isEmpty())
430 m_isReverseProxySupportEnabled = false;
434 void WebApplication::declarePublicAPI(const QString &apiPath)
436 m_publicAPIs << apiPath;
439 void WebApplication::sendFile(const Path &path)
441 const QDateTime lastModified = Utils::Fs::lastModified(path);
443 // find translated file in cache
444 if (!m_isAltUIUsed)
446 if (const auto it = m_translatedFiles.constFind(path);
447 (it != m_translatedFiles.constEnd()) && (lastModified <= it->lastModified))
449 print(it->data, it->mimeType);
450 setHeader({Http::HEADER_CACHE_CONTROL, getCachingInterval(it->mimeType)});
451 return;
455 QFile file {path.data()};
456 if (!file.open(QIODevice::ReadOnly))
458 qDebug("File %s was not found!", qUtf8Printable(path.toString()));
459 throw NotFoundHTTPError();
462 if (file.size() > MAX_ALLOWED_FILESIZE)
464 qWarning("%s: exceeded the maximum allowed file size!", qUtf8Printable(path.toString()));
465 throw InternalServerErrorHTTPError(tr("Exceeded the maximum allowed file size (%1)!")
466 .arg(Utils::Misc::friendlyUnit(MAX_ALLOWED_FILESIZE)));
469 QByteArray data {file.readAll()};
470 file.close();
472 const QMimeType mimeType = QMimeDatabase().mimeTypeForFileNameAndData(path.data(), data);
473 const bool isTranslatable = !m_isAltUIUsed && mimeType.inherits(u"text/plain"_qs);
475 // Translate the file
476 if (isTranslatable)
478 auto dataStr = QString::fromUtf8(data);
479 translateDocument(dataStr);
480 data = dataStr.toUtf8();
482 m_translatedFiles[path] = {data, mimeType.name(), lastModified}; // caching translated file
485 print(data, mimeType.name());
486 setHeader({Http::HEADER_CACHE_CONTROL, getCachingInterval(mimeType.name())});
489 Http::Response WebApplication::processRequest(const Http::Request &request, const Http::Environment &env)
491 m_currentSession = nullptr;
492 m_request = request;
493 m_env = env;
494 m_params.clear();
496 if (m_request.method == Http::METHOD_GET)
498 for (auto iter = m_request.query.cbegin(); iter != m_request.query.cend(); ++iter)
499 m_params[iter.key()] = QString::fromUtf8(iter.value());
501 else
503 m_params = m_request.posts;
506 // clear response
507 clear();
511 // block suspicious requests
512 if ((m_isCSRFProtectionEnabled && isCrossSiteRequest(m_request))
513 || (m_isHostHeaderValidationEnabled && !validateHostHeader(m_domainList)))
515 throw UnauthorizedHTTPError();
518 // reverse proxy resolve client address
519 m_clientAddress = resolveClientAddress();
521 sessionInitialize();
522 doProcessRequest();
524 catch (const HTTPError &error)
526 status(error.statusCode(), error.statusText());
527 print((!error.message().isEmpty() ? error.message() : error.statusText()), Http::CONTENT_TYPE_TXT);
530 for (const Http::Header &prebuiltHeader : asConst(m_prebuiltHeaders))
531 setHeader(prebuiltHeader);
533 return response();
536 QString WebApplication::clientId() const
538 return m_clientAddress.toString();
541 void WebApplication::sessionInitialize()
543 Q_ASSERT(!m_currentSession);
545 const QString sessionId {parseCookie(m_request.headers.value(u"cookie"_qs)).value(QString::fromLatin1(C_SID))};
547 // TODO: Additional session check
549 if (!sessionId.isEmpty())
551 m_currentSession = m_sessions.value(sessionId);
552 if (m_currentSession)
554 if (m_currentSession->hasExpired(m_sessionTimeout))
556 // session is outdated - removing it
557 delete m_sessions.take(sessionId);
558 m_currentSession = nullptr;
560 else
562 m_currentSession->updateTimestamp();
565 else
567 qDebug() << Q_FUNC_INFO << "session does not exist!";
571 if (!m_currentSession && !isAuthNeeded())
572 sessionStart();
575 QString WebApplication::generateSid() const
577 QString sid;
581 const quint32 tmp[] =
582 {Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()
583 , Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()};
584 sid = QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(tmp), sizeof(tmp)).toBase64());
586 while (m_sessions.contains(sid));
588 return sid;
591 bool WebApplication::isAuthNeeded()
593 if (!m_isLocalAuthEnabled && Utils::Net::isLoopbackAddress(m_clientAddress))
594 return false;
595 if (m_isAuthSubnetWhitelistEnabled && Utils::Net::isIPInSubnets(m_clientAddress, m_authSubnetWhitelist))
596 return false;
597 return true;
600 bool WebApplication::isPublicAPI(const QString &scope, const QString &action) const
602 return m_publicAPIs.contains(u"%1/%2"_qs.arg(scope, action));
605 void WebApplication::sessionStart()
607 Q_ASSERT(!m_currentSession);
609 // remove outdated sessions
610 Algorithm::removeIf(m_sessions, [this](const QString &, const WebSession *session)
612 if (session->hasExpired(m_sessionTimeout))
614 delete session;
615 return true;
618 return false;
621 m_currentSession = new WebSession(generateSid(), app());
622 m_currentSession->registerAPIController<AppController>(u"app"_qs);
623 m_currentSession->registerAPIController<LogController>(u"log"_qs);
624 m_currentSession->registerAPIController<RSSController>(u"rss"_qs);
625 m_currentSession->registerAPIController<SearchController>(u"search"_qs);
626 m_currentSession->registerAPIController<SyncController>(u"sync"_qs);
627 m_currentSession->registerAPIController<TorrentsController>(u"torrents"_qs);
628 m_currentSession->registerAPIController<TransferController>(u"transfer"_qs);
629 m_sessions[m_currentSession->id()] = m_currentSession;
631 QNetworkCookie cookie(C_SID, m_currentSession->id().toUtf8());
632 cookie.setHttpOnly(true);
633 cookie.setSecure(m_isSecureCookieEnabled && m_isHttpsEnabled);
634 cookie.setPath(u"/"_qs);
635 QByteArray cookieRawForm = cookie.toRawForm();
636 if (m_isCSRFProtectionEnabled)
637 cookieRawForm.append("; SameSite=Strict");
638 setHeader({Http::HEADER_SET_COOKIE, QString::fromLatin1(cookieRawForm)});
641 void WebApplication::sessionEnd()
643 Q_ASSERT(m_currentSession);
645 QNetworkCookie cookie(C_SID);
646 cookie.setPath(u"/"_qs);
647 cookie.setExpirationDate(QDateTime::currentDateTime().addDays(-1));
649 delete m_sessions.take(m_currentSession->id());
650 m_currentSession = nullptr;
652 setHeader({Http::HEADER_SET_COOKIE, QString::fromLatin1(cookie.toRawForm())});
655 bool WebApplication::isCrossSiteRequest(const Http::Request &request) const
657 // https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Verifying_Same_Origin_with_Standard_Headers
659 const auto isSameOrigin = [](const QUrl &left, const QUrl &right) -> bool
661 // [rfc6454] 5. Comparing Origins
662 return ((left.port() == right.port())
663 // && (left.scheme() == right.scheme()) // not present in this context
664 && (left.host() == right.host()));
667 const QString targetOrigin = request.headers.value(Http::HEADER_X_FORWARDED_HOST, request.headers.value(Http::HEADER_HOST));
668 const QString originValue = request.headers.value(Http::HEADER_ORIGIN);
669 const QString refererValue = request.headers.value(Http::HEADER_REFERER);
671 if (originValue.isEmpty() && refererValue.isEmpty())
673 // owasp.org recommends to block this request, but doing so will inevitably lead Web API users to spoof headers
674 // so lets be permissive here
675 return false;
678 // sent with CORS requests, as well as with POST requests
679 if (!originValue.isEmpty())
681 const bool isInvalid = !isSameOrigin(urlFromHostHeader(targetOrigin), originValue);
682 if (isInvalid)
683 LogMsg(tr("WebUI: Origin header & Target origin mismatch! Source IP: '%1'. Origin header: '%2'. Target origin: '%3'")
684 .arg(m_env.clientAddress.toString(), originValue, targetOrigin)
685 , Log::WARNING);
686 return isInvalid;
689 if (!refererValue.isEmpty())
691 const bool isInvalid = !isSameOrigin(urlFromHostHeader(targetOrigin), refererValue);
692 if (isInvalid)
693 LogMsg(tr("WebUI: Referer header & Target origin mismatch! Source IP: '%1'. Referer header: '%2'. Target origin: '%3'")
694 .arg(m_env.clientAddress.toString(), refererValue, targetOrigin)
695 , Log::WARNING);
696 return isInvalid;
699 return true;
702 bool WebApplication::validateHostHeader(const QStringList &domains) const
704 const QUrl hostHeader = urlFromHostHeader(m_request.headers[Http::HEADER_HOST]);
705 const QString requestHost = hostHeader.host();
707 // (if present) try matching host header's port with local port
708 const int requestPort = hostHeader.port();
709 if ((requestPort != -1) && (m_env.localPort != requestPort))
711 LogMsg(tr("WebUI: Invalid Host header, port mismatch. Request source IP: '%1'. Server port: '%2'. Received Host header: '%3'")
712 .arg(m_env.clientAddress.toString()).arg(m_env.localPort)
713 .arg(m_request.headers[Http::HEADER_HOST])
714 , Log::WARNING);
715 return false;
718 // try matching host header with local address
719 const bool sameAddr = m_env.localAddress.isEqual(QHostAddress(requestHost));
721 if (sameAddr)
722 return true;
724 // try matching host header with domain list
725 for (const auto &domain : domains)
727 const QRegularExpression domainRegex {Utils::String::wildcardToRegexPattern(domain), QRegularExpression::CaseInsensitiveOption};
728 if (requestHost.contains(domainRegex))
729 return true;
732 LogMsg(tr("WebUI: Invalid Host header. Request source IP: '%1'. Received Host header: '%2'")
733 .arg(m_env.clientAddress.toString(), m_request.headers[Http::HEADER_HOST])
734 , Log::WARNING);
735 return false;
738 QHostAddress WebApplication::resolveClientAddress() const
740 if (!m_isReverseProxySupportEnabled)
741 return m_env.clientAddress;
743 // Only reverse proxy can overwrite client address
744 if (!Utils::Net::isIPInSubnets(m_env.clientAddress, m_trustedReverseProxyList))
745 return m_env.clientAddress;
747 const QString forwardedFor = m_request.headers.value(Http::HEADER_X_FORWARDED_FOR);
749 if (!forwardedFor.isEmpty())
751 // client address is the 1st global IP in X-Forwarded-For or, if none available, the 1st IP in the list
752 const QStringList remoteIpList = forwardedFor.split(u',', Qt::SkipEmptyParts);
754 if (!remoteIpList.isEmpty())
756 QHostAddress clientAddress;
758 for (const QString &remoteIp : remoteIpList)
760 if (clientAddress.setAddress(remoteIp) && clientAddress.isGlobal())
761 return clientAddress;
764 if (clientAddress.setAddress(remoteIpList[0]))
765 return clientAddress;
769 return m_env.clientAddress;
772 // WebSession
774 WebSession::WebSession(const QString &sid, IApplication *app)
775 : ApplicationComponent(app)
776 , m_sid {sid}
778 updateTimestamp();
781 QString WebSession::id() const
783 return m_sid;
786 bool WebSession::hasExpired(const qint64 seconds) const
788 if (seconds <= 0)
789 return false;
790 return m_timer.hasExpired(seconds * 1000);
793 void WebSession::updateTimestamp()
795 m_timer.start();
798 APIController *WebSession::getAPIController(const QString &scope) const
800 return m_apiControllers.value(scope);