2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2014-2024 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2024 Radu Carpa <radu.carpa@cern.ch>
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 "webapplication.h"
39 #include <QJsonDocument>
40 #include <QMetaObject>
41 #include <QMimeDatabase>
43 #include <QNetworkCookie>
44 #include <QRegularExpression>
49 #include "base/algorithm.h"
50 #include "base/bittorrent/torrentcreationmanager.h"
51 #include "base/http/httperror.h"
52 #include "base/logger.h"
53 #include "base/preferences.h"
54 #include "base/types.h"
55 #include "base/utils/fs.h"
56 #include "base/utils/io.h"
57 #include "base/utils/misc.h"
58 #include "base/utils/random.h"
59 #include "base/utils/string.h"
60 #include "api/apierror.h"
61 #include "api/appcontroller.h"
62 #include "api/authcontroller.h"
63 #include "api/logcontroller.h"
64 #include "api/rsscontroller.h"
65 #include "api/searchcontroller.h"
66 #include "api/synccontroller.h"
67 #include "api/torrentcreatorcontroller.h"
68 #include "api/torrentscontroller.h"
69 #include "api/transfercontroller.h"
70 #include "freediskspacechecker.h"
72 const int MAX_ALLOWED_FILESIZE
= 10 * 1024 * 1024;
73 const QString DEFAULT_SESSION_COOKIE_NAME
= u
"SID"_s
;
75 const QString WWW_FOLDER
= u
":/www"_s
;
76 const QString PUBLIC_FOLDER
= u
"/public"_s
;
77 const QString PRIVATE_FOLDER
= u
"/private"_s
;
79 using namespace std::chrono_literals
;
81 const std::chrono::seconds FREEDISKSPACE_CHECK_TIMEOUT
= 30s
;
85 QStringMap
parseCookie(const QStringView cookieStr
)
87 // [rfc6265] 4.2.1. Syntax
89 const QList
<QStringView
> cookies
= cookieStr
.split(u
';', Qt::SkipEmptyParts
);
91 for (const auto &cookie
: cookies
)
93 const int idx
= cookie
.indexOf(u
'=');
97 const QString name
= cookie
.left(idx
).trimmed().toString();
98 const QString value
= Utils::String::unquote(cookie
.mid(idx
+ 1).trimmed()).toString();
99 ret
.insert(name
, value
);
104 QUrl
urlFromHostHeader(const QString
&hostHeader
)
106 if (!hostHeader
.contains(u
"://"))
107 return {u
"http://"_s
+ hostHeader
};
111 QString
getCachingInterval(QString contentType
)
113 contentType
= contentType
.toLower();
115 if (contentType
.startsWith(u
"image/"))
116 return u
"private, max-age=604800"_s
; // 1 week
118 if ((contentType
== Http::CONTENT_TYPE_CSS
) || (contentType
== Http::CONTENT_TYPE_JS
))
120 // short interval in case of program update
121 return u
"private, max-age=43200"_s
; // 12 hrs
124 return u
"no-store"_s
;
127 QString
createLanguagesOptionsHtml()
129 // List language files
130 const QStringList langFiles
= QDir(u
":/www/translations"_s
)
131 .entryList({u
"webui_*.qm"_s
}, QDir::Files
, QDir::Name
);
133 QStringList languages
;
134 languages
.reserve(langFiles
.size());
136 for (const QString
&langFile
: langFiles
)
138 const auto langCode
= QStringView(langFile
).sliced(6).chopped(3); // remove "webui_" and ".qm"
139 const QString entry
= u
"<option value=\"%1\">%2</option>"_s
140 .arg(langCode
, Utils::Misc::languageToLocalizedString(langCode
));
141 languages
.append(entry
);
144 return languages
.join(u
'\n');
147 bool isValidCookieName(const QString
&cookieName
)
149 if (cookieName
.isEmpty() || (cookieName
.size() > 128))
152 const QRegularExpression invalidNameRegex
{u
"[^a-zA-Z0-9_\\-]"_s
};
153 if (invalidNameRegex
.match(cookieName
).hasMatch())
160 WebApplication::WebApplication(IApplication
*app
, QObject
*parent
)
161 : ApplicationComponent(app
, parent
)
162 , m_cacheID
{QString::number(Utils::Random::rand(), 36)}
163 , m_authController
{new AuthController(this, app
, this)}
164 , m_workerThread
{new QThread
}
165 , m_freeDiskSpaceChecker
{new FreeDiskSpaceChecker
}
166 , m_freeDiskSpaceCheckingTimer
{new QTimer(this)}
167 , m_torrentCreationManager
{new BitTorrent::TorrentCreationManager(app
, this)}
169 declarePublicAPI(u
"auth/login"_s
);
172 connect(Preferences::instance(), &Preferences::changed
, this, &WebApplication::configure
);
174 m_sessionCookieName
= Preferences::instance()->getWebAPISessionCookieName();
175 if (!isValidCookieName(m_sessionCookieName
))
177 if (!m_sessionCookieName
.isEmpty())
179 LogMsg(tr("Unacceptable session cookie name is specified: '%1'. Default one is used.")
180 .arg(m_sessionCookieName
), Log::WARNING
);
182 m_sessionCookieName
= DEFAULT_SESSION_COOKIE_NAME
;
185 m_freeDiskSpaceChecker
->moveToThread(m_workerThread
.get());
186 connect(m_workerThread
.get(), &QThread::finished
, m_freeDiskSpaceChecker
, &QObject::deleteLater
);
187 m_workerThread
->start();
189 m_freeDiskSpaceCheckingTimer
->setInterval(FREEDISKSPACE_CHECK_TIMEOUT
);
190 m_freeDiskSpaceCheckingTimer
->setSingleShot(true);
191 connect(m_freeDiskSpaceCheckingTimer
, &QTimer::timeout
, m_freeDiskSpaceChecker
, &FreeDiskSpaceChecker::check
);
192 connect(m_freeDiskSpaceChecker
, &FreeDiskSpaceChecker::checked
, m_freeDiskSpaceCheckingTimer
, qOverload
<>(&QTimer::start
));
193 QMetaObject::invokeMethod(m_freeDiskSpaceChecker
, &FreeDiskSpaceChecker::check
);
196 WebApplication::~WebApplication()
198 // cleanup sessions data
199 qDeleteAll(m_sessions
);
202 void WebApplication::sendWebUIFile()
204 if (request().path
.contains(u
'\\'))
205 throw BadRequestHTTPError();
207 if (const QList
<QStringView
> pathItems
= QStringView(request().path
).split(u
'/', Qt::SkipEmptyParts
)
208 ; pathItems
.contains(u
".") || pathItems
.contains(u
".."))
210 throw BadRequestHTTPError();
213 const QString path
= (request().path
!= u
"/")
217 Path localPath
= m_rootFolder
218 / Path(session() ? PRIVATE_FOLDER
: PUBLIC_FOLDER
)
220 if (!localPath
.exists() && session())
222 // try to send public file if there is no private one
223 localPath
= m_rootFolder
/ Path(PUBLIC_FOLDER
) / Path(path
);
228 if (!Utils::Fs::isRegularFile(localPath
))
229 throw InternalServerErrorHTTPError(tr("Unacceptable file type, only regular file is allowed."));
231 const QString rootFolder
= m_rootFolder
.data();
233 QFileInfo fileInfo
{localPath
.parentPath().data()};
234 while (fileInfo
.path() != rootFolder
)
236 if (fileInfo
.isSymLink())
237 throw InternalServerErrorHTTPError(tr("Symlinks inside alternative UI folder are forbidden."));
239 fileInfo
.setFile(fileInfo
.path());
246 void WebApplication::translateDocument(QString
&data
) const
248 const QRegularExpression
regex(u
"QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\]"_s
);
252 while (i
< data
.size() && found
)
254 QRegularExpressionMatch regexMatch
;
255 i
= data
.indexOf(regex
, i
, ®exMatch
);
258 const QString sourceText
= regexMatch
.captured(1);
259 const QString context
= regexMatch
.captured(3);
261 const QString loadedText
= m_translationFileLoaded
262 ? m_translator
.translate(context
.toUtf8().constData(), sourceText
.toUtf8().constData())
264 // `loadedText` is empty when translation is not provided
265 // it should fallback to `sourceText`
266 QString translation
= loadedText
.isEmpty() ? sourceText
: loadedText
;
268 // Use HTML code for quotes to prevent issues with JS
269 translation
.replace(u
'\'', u
"'"_s
);
270 translation
.replace(u
'\"', u
"""_s
);
272 data
.replace(i
, regexMatch
.capturedLength(), translation
);
273 i
+= translation
.length();
277 found
= false; // no more translatable strings
280 data
.replace(u
"${LANG}"_s
, m_currentLocale
.left(2));
281 data
.replace(u
"${CACHEID}"_s
, m_cacheID
);
285 WebSession
*WebApplication::session()
287 return m_currentSession
;
290 const Http::Request
&WebApplication::request() const
295 const Http::Environment
&WebApplication::env() const
300 void WebApplication::setUsername(const QString
&username
)
302 m_authController
->setUsername(username
);
305 void WebApplication::setPasswordHash(const QByteArray
&passwordHash
)
307 m_authController
->setPasswordHash(passwordHash
);
310 void WebApplication::doProcessRequest()
312 const QRegularExpressionMatch match
= m_apiPathPattern
.match(request().path
);
313 if (!match
.hasMatch())
319 const QString action
= match
.captured(u
"action"_s
);
320 const QString scope
= match
.captured(u
"scope"_s
);
322 // Check public/private scope
323 if (!session() && !isPublicAPI(scope
, action
))
324 throw ForbiddenHTTPError();
327 APIController
*controller
= nullptr;
329 controller
= session()->getAPIController(scope
);
332 if (scope
== u
"auth")
333 controller
= m_authController
;
335 throw NotFoundHTTPError();
338 // Filter HTTP methods
339 const auto allowedMethodIter
= m_allowedMethod
.find({scope
, action
});
340 if (allowedMethodIter
== m_allowedMethod
.end())
342 // by default allow both GET, POST methods
343 if ((m_request
.method
!= Http::METHOD_GET
) && (m_request
.method
!= Http::METHOD_POST
))
344 throw MethodNotAllowedHTTPError();
348 if (*allowedMethodIter
!= m_request
.method
)
349 throw MethodNotAllowedHTTPError();
353 for (const Http::UploadedFile
&torrent
: request().files
)
354 data
[torrent
.filename
] = torrent
.data
;
358 const APIResult result
= controller
->run(action
, m_params
, data
);
359 switch (result
.data
.userType())
361 case QMetaType::QJsonDocument
:
362 print(result
.data
.toJsonDocument().toJson(QJsonDocument::Compact
), Http::CONTENT_TYPE_JSON
);
364 case QMetaType::QByteArray
:
366 const auto resultData
= result
.data
.toByteArray();
367 print(resultData
, (!result
.mimeType
.isEmpty() ? result
.mimeType
: Http::CONTENT_TYPE_TXT
));
368 if (!result
.filename
.isEmpty())
370 setHeader({u
"Content-Disposition"_s
, u
"attachment; filename=\"%1\""_s
.arg(result
.filename
)});
374 case QMetaType::QString
:
376 print(result
.data
.toString(), Http::CONTENT_TYPE_TXT
);
380 catch (const APIError
&error
)
382 // re-throw as HTTPError
383 switch (error
.type())
385 case APIErrorType::AccessDenied
:
386 throw ForbiddenHTTPError(error
.message());
387 case APIErrorType::BadData
:
388 throw UnsupportedMediaTypeHTTPError(error
.message());
389 case APIErrorType::BadParams
:
390 throw BadRequestHTTPError(error
.message());
391 case APIErrorType::Conflict
:
392 throw ConflictHTTPError(error
.message());
393 case APIErrorType::NotFound
:
394 throw NotFoundHTTPError(error
.message());
401 void WebApplication::configure()
403 const auto *pref
= Preferences::instance();
405 const bool isAltUIUsed
= pref
->isAltWebUIEnabled();
406 const Path rootFolder
= (!isAltUIUsed
? Path(WWW_FOLDER
) : pref
->getWebUIRootFolder());
407 if ((isAltUIUsed
!= m_isAltUIUsed
) || (rootFolder
!= m_rootFolder
))
409 m_isAltUIUsed
= isAltUIUsed
;
410 m_rootFolder
= rootFolder
;
411 m_translatedFiles
.clear();
413 LogMsg(tr("Using built-in WebUI."));
415 LogMsg(tr("Using custom WebUI. Location: \"%1\".").arg(m_rootFolder
.toString()));
418 const QString newLocale
= pref
->getLocale();
419 if (m_currentLocale
!= newLocale
)
421 m_currentLocale
= newLocale
;
422 m_translatedFiles
.clear();
424 m_translationFileLoaded
= m_translator
.load((m_rootFolder
/ Path(u
"translations/webui_"_s
) + newLocale
).data());
425 if (m_translationFileLoaded
)
427 LogMsg(tr("WebUI translation for selected locale (%1) has been successfully loaded.")
432 LogMsg(tr("Couldn't load WebUI translation for selected locale (%1).").arg(newLocale
), Log::WARNING
);
436 m_isLocalAuthEnabled
= pref
->isWebUILocalAuthEnabled();
437 m_isAuthSubnetWhitelistEnabled
= pref
->isWebUIAuthSubnetWhitelistEnabled();
438 m_authSubnetWhitelist
= pref
->getWebUIAuthSubnetWhitelist();
439 m_sessionTimeout
= pref
->getWebUISessionTimeout();
441 m_domainList
= pref
->getServerDomains().split(u
';', Qt::SkipEmptyParts
);
442 std::for_each(m_domainList
.begin(), m_domainList
.end(), [](QString
&entry
) { entry
= entry
.trimmed(); });
444 m_isCSRFProtectionEnabled
= pref
->isWebUICSRFProtectionEnabled();
445 m_isSecureCookieEnabled
= pref
->isWebUISecureCookieEnabled();
446 m_isHostHeaderValidationEnabled
= pref
->isWebUIHostHeaderValidationEnabled();
447 m_isHttpsEnabled
= pref
->isWebUIHttpsEnabled();
449 m_prebuiltHeaders
.clear();
450 m_prebuiltHeaders
.push_back({Http::HEADER_X_XSS_PROTECTION
, u
"1; mode=block"_s
});
451 m_prebuiltHeaders
.push_back({Http::HEADER_X_CONTENT_TYPE_OPTIONS
, u
"nosniff"_s
});
455 m_prebuiltHeaders
.push_back({Http::HEADER_CROSS_ORIGIN_OPENER_POLICY
, u
"same-origin"_s
});
456 m_prebuiltHeaders
.push_back({Http::HEADER_REFERRER_POLICY
, u
"same-origin"_s
});
459 const bool isClickjackingProtectionEnabled
= pref
->isWebUIClickjackingProtectionEnabled();
460 if (isClickjackingProtectionEnabled
)
461 m_prebuiltHeaders
.push_back({Http::HEADER_X_FRAME_OPTIONS
, u
"SAMEORIGIN"_s
});
463 const QString contentSecurityPolicy
=
466 : u
"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self';"_s
)
467 + (isClickjackingProtectionEnabled
? u
" frame-ancestors 'self';"_s
: QString())
468 + (m_isHttpsEnabled
? u
" upgrade-insecure-requests;"_s
: QString());
469 if (!contentSecurityPolicy
.isEmpty())
470 m_prebuiltHeaders
.push_back({Http::HEADER_CONTENT_SECURITY_POLICY
, contentSecurityPolicy
});
472 if (pref
->isWebUICustomHTTPHeadersEnabled())
474 const QString customHeaders
= pref
->getWebUICustomHTTPHeaders();
475 const QList
<QStringView
> customHeaderLines
= QStringView(customHeaders
).trimmed().split(u
'\n', Qt::SkipEmptyParts
);
477 for (const QStringView line
: customHeaderLines
)
479 const int idx
= line
.indexOf(u
':');
482 // require separator `:` to be present even if `value` field can be empty
483 LogMsg(tr("Missing ':' separator in WebUI custom HTTP header: \"%1\"").arg(line
.toString()), Log::WARNING
);
487 const QString header
= line
.left(idx
).trimmed().toString();
488 const QString value
= line
.mid(idx
+ 1).trimmed().toString();
489 m_prebuiltHeaders
.push_back({header
, value
});
493 m_isReverseProxySupportEnabled
= pref
->isWebUIReverseProxySupportEnabled();
494 if (m_isReverseProxySupportEnabled
)
496 const QStringList proxyList
= pref
->getWebUITrustedReverseProxiesList().split(u
';', Qt::SkipEmptyParts
);
498 m_trustedReverseProxyList
.clear();
499 m_trustedReverseProxyList
.reserve(proxyList
.size());
501 for (QString proxy
: proxyList
)
503 if (!proxy
.contains(u
'/'))
505 const QAbstractSocket::NetworkLayerProtocol protocol
= QHostAddress(proxy
).protocol();
506 if (protocol
== QAbstractSocket::IPv4Protocol
)
508 proxy
.append(u
"/32");
510 else if (protocol
== QAbstractSocket::IPv6Protocol
)
512 proxy
.append(u
"/128");
516 const std::optional
<Utils::Net::Subnet
> subnet
= Utils::Net::parseSubnet(proxy
);
518 m_trustedReverseProxyList
.push_back(subnet
.value());
521 if (m_trustedReverseProxyList
.isEmpty())
522 m_isReverseProxySupportEnabled
= false;
526 void WebApplication::declarePublicAPI(const QString
&apiPath
)
528 m_publicAPIs
<< apiPath
;
531 void WebApplication::sendFile(const Path
&path
)
533 const QDateTime lastModified
= Utils::Fs::lastModified(path
);
535 // find translated file in cache
538 if (const auto it
= m_translatedFiles
.constFind(path
);
539 (it
!= m_translatedFiles
.constEnd()) && (lastModified
<= it
->lastModified
))
541 print(it
->data
, it
->mimeType
);
542 setHeader({Http::HEADER_CACHE_CONTROL
, getCachingInterval(it
->mimeType
)});
547 const auto readResult
= Utils::IO::readFile(path
, MAX_ALLOWED_FILESIZE
);
550 const QString message
= tr("Web server error. %1").arg(readResult
.error().message
);
552 switch (readResult
.error().status
)
554 case Utils::IO::ReadError::NotExist
:
555 qDebug("%s", qUtf8Printable(message
));
556 // don't write log messages here to avoid exhausting the disk space
557 throw NotFoundHTTPError();
559 case Utils::IO::ReadError::ExceedSize
:
560 qWarning("%s", qUtf8Printable(message
));
561 LogMsg(message
, Log::WARNING
);
562 throw InternalServerErrorHTTPError(readResult
.error().message
);
564 case Utils::IO::ReadError::Failed
:
565 case Utils::IO::ReadError::SizeMismatch
:
566 LogMsg(message
, Log::WARNING
);
567 throw InternalServerErrorHTTPError(readResult
.error().message
);
570 throw InternalServerErrorHTTPError(tr("Web server error. Unknown error."));
573 QByteArray data
= readResult
.value();
574 const QMimeType mimeType
= QMimeDatabase().mimeTypeForFileNameAndData(path
.data(), data
);
575 const bool isTranslatable
= !m_isAltUIUsed
&& mimeType
.inherits(u
"text/plain"_s
);
579 auto dataStr
= QString::fromUtf8(data
);
580 // Translate the file
581 translateDocument(dataStr
);
583 // Add the language options
584 if (path
== (m_rootFolder
/ Path(PRIVATE_FOLDER
) / Path(u
"views/preferences.html"_s
)))
585 dataStr
.replace(u
"${LANGUAGE_OPTIONS}"_s
, createLanguagesOptionsHtml());
587 data
= dataStr
.toUtf8();
588 m_translatedFiles
[path
] = {data
, mimeType
.name(), lastModified
}; // caching translated file
591 print(data
, mimeType
.name());
592 setHeader({Http::HEADER_CACHE_CONTROL
, getCachingInterval(mimeType
.name())});
595 Http::Response
WebApplication::processRequest(const Http::Request
&request
, const Http::Environment
&env
)
597 m_currentSession
= nullptr;
602 if (m_request
.method
== Http::METHOD_GET
)
604 for (auto iter
= m_request
.query
.cbegin(); iter
!= m_request
.query
.cend(); ++iter
)
605 m_params
[iter
.key()] = QString::fromUtf8(iter
.value());
609 m_params
= m_request
.posts
;
617 // block suspicious requests
618 if ((m_isCSRFProtectionEnabled
&& isCrossSiteRequest(m_request
))
619 || (m_isHostHeaderValidationEnabled
&& !validateHostHeader(m_domainList
)))
621 throw UnauthorizedHTTPError();
624 // reverse proxy resolve client address
625 m_clientAddress
= resolveClientAddress();
630 catch (const HTTPError
&error
)
632 status(error
.statusCode(), error
.statusText());
633 print((!error
.message().isEmpty() ? error
.message() : error
.statusText()), Http::CONTENT_TYPE_TXT
);
636 for (const Http::Header
&prebuiltHeader
: asConst(m_prebuiltHeaders
))
637 setHeader(prebuiltHeader
);
642 QString
WebApplication::clientId() const
644 return m_clientAddress
.toString();
647 void WebApplication::sessionInitialize()
649 Q_ASSERT(!m_currentSession
);
651 const QString sessionId
{parseCookie(m_request
.headers
.value(u
"cookie"_s
)).value(m_sessionCookieName
)};
653 // TODO: Additional session check
655 if (!sessionId
.isEmpty())
657 m_currentSession
= m_sessions
.value(sessionId
);
658 if (m_currentSession
)
660 if (m_currentSession
->hasExpired(m_sessionTimeout
))
662 // session is outdated - removing it
663 delete m_sessions
.take(sessionId
);
664 m_currentSession
= nullptr;
668 m_currentSession
->updateTimestamp();
673 qDebug() << Q_FUNC_INFO
<< "session does not exist!";
677 if (!m_currentSession
&& !isAuthNeeded())
681 QString
WebApplication::generateSid() const
687 const quint32 tmp
[] =
688 {Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()
689 , Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()};
690 sid
= QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(tmp
), sizeof(tmp
)).toBase64());
692 while (m_sessions
.contains(sid
));
697 bool WebApplication::isAuthNeeded()
699 if (!m_isLocalAuthEnabled
&& Utils::Net::isLoopbackAddress(m_clientAddress
))
701 if (m_isAuthSubnetWhitelistEnabled
&& Utils::Net::isIPInSubnets(m_clientAddress
, m_authSubnetWhitelist
))
706 bool WebApplication::isPublicAPI(const QString
&scope
, const QString
&action
) const
708 return m_publicAPIs
.contains(u
"%1/%2"_s
.arg(scope
, action
));
711 void WebApplication::sessionStart()
713 Q_ASSERT(!m_currentSession
);
715 // remove outdated sessions
716 Algorithm::removeIf(m_sessions
, [this](const QString
&, const WebSession
*session
)
718 if (session
->hasExpired(m_sessionTimeout
))
727 m_currentSession
= new WebSession(generateSid(), app());
728 m_sessions
[m_currentSession
->id()] = m_currentSession
;
730 m_currentSession
->registerAPIController(u
"app"_s
, new AppController(app(), this));
731 m_currentSession
->registerAPIController(u
"log"_s
, new LogController(app(), this));
732 m_currentSession
->registerAPIController(u
"torrentcreator"_s
, new TorrentCreatorController(m_torrentCreationManager
, app(), this));
733 m_currentSession
->registerAPIController(u
"rss"_s
, new RSSController(app(), this));
734 m_currentSession
->registerAPIController(u
"search"_s
, new SearchController(app(), this));
735 m_currentSession
->registerAPIController(u
"torrents"_s
, new TorrentsController(app(), this));
736 m_currentSession
->registerAPIController(u
"transfer"_s
, new TransferController(app(), this));
738 auto *syncController
= new SyncController(app(), this);
739 syncController
->updateFreeDiskSpace(m_freeDiskSpaceChecker
->lastResult());
740 connect(m_freeDiskSpaceChecker
, &FreeDiskSpaceChecker::checked
, syncController
, &SyncController::updateFreeDiskSpace
);
741 m_currentSession
->registerAPIController(u
"sync"_s
, syncController
);
743 QNetworkCookie cookie
{m_sessionCookieName
.toLatin1(), m_currentSession
->id().toUtf8()};
744 cookie
.setHttpOnly(true);
745 cookie
.setSecure(m_isSecureCookieEnabled
&& m_isHttpsEnabled
);
746 cookie
.setPath(u
"/"_s
);
747 QByteArray cookieRawForm
= cookie
.toRawForm();
748 if (m_isCSRFProtectionEnabled
)
749 cookieRawForm
.append("; SameSite=Strict");
750 else if (cookie
.isSecure())
751 cookieRawForm
.append("; SameSite=None");
752 setHeader({Http::HEADER_SET_COOKIE
, QString::fromLatin1(cookieRawForm
)});
755 void WebApplication::sessionEnd()
757 Q_ASSERT(m_currentSession
);
759 QNetworkCookie cookie
{m_sessionCookieName
.toLatin1()};
760 cookie
.setPath(u
"/"_s
);
761 cookie
.setExpirationDate(QDateTime::currentDateTime().addDays(-1));
763 delete m_sessions
.take(m_currentSession
->id());
764 m_currentSession
= nullptr;
766 setHeader({Http::HEADER_SET_COOKIE
, QString::fromLatin1(cookie
.toRawForm())});
769 bool WebApplication::isCrossSiteRequest(const Http::Request
&request
) const
771 // https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Verifying_Same_Origin_with_Standard_Headers
773 const auto isSameOrigin
= [](const QUrl
&left
, const QUrl
&right
) -> bool
775 // [rfc6454] 5. Comparing Origins
776 return ((left
.port() == right
.port())
777 // && (left.scheme() == right.scheme()) // not present in this context
778 && (left
.host() == right
.host()));
781 const QString targetOrigin
= request
.headers
.value(Http::HEADER_X_FORWARDED_HOST
, request
.headers
.value(Http::HEADER_HOST
));
782 const QString originValue
= request
.headers
.value(Http::HEADER_ORIGIN
);
783 const QString refererValue
= request
.headers
.value(Http::HEADER_REFERER
);
785 if (originValue
.isEmpty() && refererValue
.isEmpty())
787 // owasp.org recommends to block this request, but doing so will inevitably lead Web API users to spoof headers
788 // so lets be permissive here
792 // sent with CORS requests, as well as with POST requests
793 if (!originValue
.isEmpty())
795 const bool isInvalid
= !isSameOrigin(urlFromHostHeader(targetOrigin
), originValue
);
798 LogMsg(tr("WebUI: Origin header & Target origin mismatch! Source IP: '%1'. Origin header: '%2'. Target origin: '%3'")
799 .arg(m_env
.clientAddress
.toString(), originValue
, targetOrigin
)
805 if (!refererValue
.isEmpty())
807 const bool isInvalid
= !isSameOrigin(urlFromHostHeader(targetOrigin
), refererValue
);
810 LogMsg(tr("WebUI: Referer header & Target origin mismatch! Source IP: '%1'. Referer header: '%2'. Target origin: '%3'")
811 .arg(m_env
.clientAddress
.toString(), refererValue
, targetOrigin
)
820 bool WebApplication::validateHostHeader(const QStringList
&domains
) const
822 const QUrl hostHeader
= urlFromHostHeader(m_request
.headers
[Http::HEADER_HOST
]);
823 const QString requestHost
= hostHeader
.host();
825 // (if present) try matching host header's port with local port
826 const int requestPort
= hostHeader
.port();
827 if ((requestPort
!= -1) && (m_env
.localPort
!= requestPort
))
829 LogMsg(tr("WebUI: Invalid Host header, port mismatch. Request source IP: '%1'. Server port: '%2'. Received Host header: '%3'")
830 .arg(m_env
.clientAddress
.toString()).arg(m_env
.localPort
)
831 .arg(m_request
.headers
[Http::HEADER_HOST
])
836 // try matching host header with local address
837 const bool sameAddr
= m_env
.localAddress
.isEqual(QHostAddress(requestHost
));
842 // try matching host header with domain list
843 for (const auto &domain
: domains
)
845 const QRegularExpression domainRegex
{Utils::String::wildcardToRegexPattern(domain
), QRegularExpression::CaseInsensitiveOption
};
846 if (requestHost
.contains(domainRegex
))
850 LogMsg(tr("WebUI: Invalid Host header. Request source IP: '%1'. Received Host header: '%2'")
851 .arg(m_env
.clientAddress
.toString(), m_request
.headers
[Http::HEADER_HOST
])
856 QHostAddress
WebApplication::resolveClientAddress() const
858 if (!m_isReverseProxySupportEnabled
)
859 return m_env
.clientAddress
;
861 // Only reverse proxy can overwrite client address
862 if (!Utils::Net::isIPInSubnets(m_env
.clientAddress
, m_trustedReverseProxyList
))
863 return m_env
.clientAddress
;
865 const QString forwardedFor
= m_request
.headers
.value(Http::HEADER_X_FORWARDED_FOR
);
867 if (!forwardedFor
.isEmpty())
869 // client address is the 1st global IP in X-Forwarded-For or, if none available, the 1st IP in the list
870 const QStringList remoteIpList
= forwardedFor
.split(u
',', Qt::SkipEmptyParts
);
872 if (!remoteIpList
.isEmpty())
874 QHostAddress clientAddress
;
876 for (const QString
&remoteIp
: remoteIpList
)
878 if (clientAddress
.setAddress(remoteIp
) && clientAddress
.isGlobal())
879 return clientAddress
;
882 if (clientAddress
.setAddress(remoteIpList
[0]))
883 return clientAddress
;
887 return m_env
.clientAddress
;
892 WebSession::WebSession(const QString
&sid
, IApplication
*app
)
893 : ApplicationComponent(app
)
899 QString
WebSession::id() const
904 bool WebSession::hasExpired(const qint64 seconds
) const
908 return m_timer
.hasExpired(seconds
* 1000);
911 void WebSession::updateTimestamp()
916 void WebSession::registerAPIController(const QString
&scope
, APIController
*controller
)
918 Q_ASSERT(controller
);
919 m_apiControllers
[scope
] = controller
;
922 APIController
*WebSession::getAPIController(const QString
&scope
) const
924 return m_apiControllers
.value(scope
);