Improve coding style

This commit is contained in:
Vladimir Golovnev (Glassez)
2020-11-16 10:02:11 +03:00
committed by sledgehammer999
parent d3f46452a9
commit 1728c16580
147 changed files with 4454 additions and 2227 deletions

View File

@@ -56,7 +56,8 @@ DNSUpdater::DNSUpdater(QObject *parent)
// Check lastUpdate to avoid flooding
if (!m_lastIPCheckTime.isValid()
|| (m_lastIPCheckTime.secsTo(QDateTime::currentDateTime()) * 1000 > IP_CHECK_INTERVAL_MS)) {
|| (m_lastIPCheckTime.secsTo(QDateTime::currentDateTime()) * 1000 > IP_CHECK_INTERVAL_MS))
{
checkPublicIP();
}
}
@@ -82,30 +83,36 @@ void DNSUpdater::checkPublicIP()
void DNSUpdater::ipRequestFinished(const DownloadResult &result)
{
if (result.status != DownloadStatus::Success) {
if (result.status != DownloadStatus::Success)
{
qWarning() << "IP request failed:" << result.errorString;
return;
}
// Parse response
const QRegularExpressionMatch ipRegexMatch = QRegularExpression("Current IP Address:\\s+([^<]+)</body>").match(result.data);
if (ipRegexMatch.hasMatch()) {
if (ipRegexMatch.hasMatch())
{
QString ipStr = ipRegexMatch.captured(1);
qDebug() << Q_FUNC_INFO << "Regular expression captured the following IP:" << ipStr;
QHostAddress newIp(ipStr);
if (!newIp.isNull()) {
if (m_lastIP != newIp) {
if (!newIp.isNull())
{
if (m_lastIP != newIp)
{
qDebug() << Q_FUNC_INFO << "The IP address changed, report the change to DynDNS...";
qDebug() << m_lastIP.toString() << "->" << newIp.toString();
m_lastIP = newIp;
updateDNSService();
}
}
else {
else
{
qWarning() << Q_FUNC_INFO << "Failed to construct a QHostAddress from the IP string";
}
}
else {
else
{
qWarning() << Q_FUNC_INFO << "Regular expression failed to capture the IP address";
}
}
@@ -133,7 +140,8 @@ QString DNSUpdater::getUpdateUrl() const
Q_ASSERT(!m_lastIP.isNull());
// Service specific
switch (m_service) {
switch (m_service)
{
case DNS::DYNDNS:
url.setHost("members.dyndns.org");
break;
@@ -171,12 +179,14 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
const QString code = reply.split(' ').first();
qDebug() << Q_FUNC_INFO << "Code:" << code;
if ((code == "good") || (code == "nochg")) {
if ((code == "good") || (code == "nochg"))
{
logger->addMessage(tr("Your dynamic DNS was successfully updated."), Log::INFO);
return;
}
if ((code == "911") || (code == "dnserr")) {
if ((code == "911") || (code == "dnserr"))
{
logger->addMessage(tr("Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes."), Log::CRITICAL);
m_lastIP.clear();
// It will retry in 30 minutes because the timer was not stopped
@@ -186,33 +196,38 @@ void DNSUpdater::processIPUpdateReply(const QString &reply)
// Everything below is an error, stop updating until the user updates something
m_ipCheckTimer.stop();
m_lastIP.clear();
if (code == "nohost") {
if (code == "nohost")
{
logger->addMessage(tr("Dynamic DNS error: hostname supplied does not exist under specified account."), Log::CRITICAL);
m_state = INVALID_CREDS;
return;
}
if (code == "badauth") {
if (code == "badauth")
{
logger->addMessage(tr("Dynamic DNS error: Invalid username/password."), Log::CRITICAL);
m_state = INVALID_CREDS;
return;
}
if (code == "badagent") {
if (code == "badagent")
{
logger->addMessage(tr("Dynamic DNS error: qBittorrent was blacklisted by the service, please report a bug at http://bugs.qbittorrent.org."),
Log::CRITICAL);
m_state = FATAL;
return;
}
if (code == "!donator") {
if (code == "!donator")
{
logger->addMessage(tr("Dynamic DNS error: %1 was returned by the service, please report a bug at http://bugs.qbittorrent.org.").arg("!donator"),
Log::CRITICAL);
m_state = FATAL;
return;
}
if (code == "abuse") {
if (code == "abuse")
{
logger->addMessage(tr("Dynamic DNS error: Your username was blocked due to abuse."), Log::CRITICAL);
m_state = FATAL;
}
@@ -225,14 +240,17 @@ void DNSUpdater::updateCredentials()
Logger *const logger = Logger::instance();
bool change = false;
// Get DNS service information
if (m_service != pref->getDynDNSService()) {
if (m_service != pref->getDynDNSService())
{
m_service = pref->getDynDNSService();
change = true;
}
if (m_domain != pref->getDynDomainName()) {
if (m_domain != pref->getDynDomainName())
{
m_domain = pref->getDynDomainName();
const QRegularExpressionMatch domainRegexMatch = QRegularExpression("^(?:(?!\\d|-)[a-zA-Z0-9\\-]{1,63}\\.)+[a-zA-Z]{2,}$").match(m_domain);
if (!domainRegexMatch.hasMatch()) {
if (!domainRegexMatch.hasMatch())
{
logger->addMessage(tr("Dynamic DNS error: supplied domain name is invalid."), Log::CRITICAL);
m_lastIP.clear();
m_ipCheckTimer.stop();
@@ -241,9 +259,11 @@ void DNSUpdater::updateCredentials()
}
change = true;
}
if (m_username != pref->getDynDNSUsername()) {
if (m_username != pref->getDynDNSUsername())
{
m_username = pref->getDynDNSUsername();
if (m_username.length() < 4) {
if (m_username.length() < 4)
{
logger->addMessage(tr("Dynamic DNS error: supplied username is too short."), Log::CRITICAL);
m_lastIP.clear();
m_ipCheckTimer.stop();
@@ -252,9 +272,11 @@ void DNSUpdater::updateCredentials()
}
change = true;
}
if (m_password != pref->getDynDNSPassword()) {
if (m_password != pref->getDynDNSPassword())
{
m_password = pref->getDynDNSPassword();
if (m_password.length() < 4) {
if (m_password.length() < 4)
{
logger->addMessage(tr("Dynamic DNS error: supplied password is too short."), Log::CRITICAL);
m_lastIP.clear();
m_ipCheckTimer.stop();
@@ -264,7 +286,8 @@ void DNSUpdater::updateCredentials()
change = true;
}
if ((m_state == INVALID_CREDS) && change) {
if ((m_state == INVALID_CREDS) && change)
{
m_state = OK; // Try again
m_ipCheckTimer.start();
checkPublicIP();
@@ -273,7 +296,8 @@ void DNSUpdater::updateCredentials()
QUrl DNSUpdater::getRegistrationUrl(const int service)
{
switch (service) {
switch (service)
{
case DNS::DYNDNS:
return {"https://www.dyndns.com/account/services/hosts/add.html"};
case DNS::NOIP:

View File

@@ -66,10 +66,12 @@ DownloadHandlerImpl::DownloadHandlerImpl(Net::DownloadManager *manager, const Ne
void DownloadHandlerImpl::cancel()
{
if (m_reply) {
if (m_reply)
{
m_reply->abort();
}
else {
else
{
setError(errorCodeToString(QNetworkReply::OperationCanceledError));
finish();
}
@@ -103,7 +105,8 @@ void DownloadHandlerImpl::processFinishedDownload()
qDebug("Download finished: %s", qUtf8Printable(url()));
// Check if the request was successful
if (m_reply->error() != QNetworkReply::NoError) {
if (m_reply->error() != QNetworkReply::NoError)
{
// Failure
qDebug("Download failure (%s), reason: %s", qUtf8Printable(url()), qUtf8Printable(errorCodeToString(m_reply->error())));
setError(errorCodeToString(m_reply->error()));
@@ -113,7 +116,8 @@ void DownloadHandlerImpl::processFinishedDownload()
// Check if the server ask us to redirect somewhere else
const QVariant redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (redirection.isValid()) {
if (redirection.isValid())
{
handleRedirection(redirection.toUrl());
return;
}
@@ -123,7 +127,8 @@ void DownloadHandlerImpl::processFinishedDownload()
? Utils::Gzip::decompress(m_reply->readAll())
: m_reply->readAll();
if (m_downloadRequest.saveToFile()) {
if (m_downloadRequest.saveToFile())
{
QString filePath;
if (saveToFile(m_result.data, filePath))
m_result.filePath = filePath;
@@ -136,13 +141,15 @@ void DownloadHandlerImpl::processFinishedDownload()
void DownloadHandlerImpl::checkDownloadSize(const qint64 bytesReceived, const qint64 bytesTotal)
{
if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit())) {
if ((bytesTotal > 0) && (bytesTotal <= m_downloadRequest.limit()))
{
// Total number of bytes is available
disconnect(m_reply, &QNetworkReply::downloadProgress, this, &DownloadHandlerImpl::checkDownloadSize);
return;
}
if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit())) {
if ((bytesTotal > m_downloadRequest.limit()) || (bytesReceived > m_downloadRequest.limit()))
{
m_reply->abort();
setError(tr("The file size (%1) exceeds the download limit (%2)")
.arg(Utils::Misc::friendlyUnit(bytesTotal)
@@ -153,7 +160,8 @@ void DownloadHandlerImpl::checkDownloadSize(const qint64 bytesReceived, const qi
void DownloadHandlerImpl::handleRedirection(const QUrl &newUrl)
{
if (m_redirectionCount >= MAX_REDIRECTIONS) {
if (m_redirectionCount >= MAX_REDIRECTIONS)
{
setError(tr("Exceeded max redirections (%1)").arg(MAX_REDIRECTIONS));
finish();
return;
@@ -165,7 +173,8 @@ void DownloadHandlerImpl::handleRedirection(const QUrl &newUrl)
qDebug("Redirecting from %s to %s...", qUtf8Printable(m_reply->url().toString()), qUtf8Printable(newUrlString));
// Redirect to magnet workaround
if (newUrlString.startsWith("magnet:", Qt::CaseInsensitive)) {
if (newUrlString.startsWith("magnet:", Qt::CaseInsensitive))
{
qDebug("Magnet redirect detected.");
m_result.status = Net::DownloadStatus::RedirectedToMagnet;
m_result.magnet = newUrlString;
@@ -199,7 +208,8 @@ void DownloadHandlerImpl::finish()
QString DownloadHandlerImpl::errorCodeToString(const QNetworkReply::NetworkError status)
{
switch (status) {
switch (status)
{
case QNetworkReply::HostNotFoundError:
return tr("The remote host name was not found (invalid hostname)");
case QNetworkReply::OperationCanceledError:

View File

@@ -60,7 +60,8 @@ namespace
{
const QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = Preferences::instance()->getNetworkCookies();
for (const QNetworkCookie &cookie : asConst(Preferences::instance()->getNetworkCookies())) {
for (const QNetworkCookie &cookie : asConst(Preferences::instance()->getNetworkCookies()))
{
if (cookie.isSessionCookie() || (cookie.expirationDate() <= now))
cookies.removeAll(cookie);
}
@@ -72,7 +73,8 @@ namespace
{
const QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = allCookies();
for (const QNetworkCookie &cookie : asConst(allCookies())) {
for (const QNetworkCookie &cookie : asConst(allCookies()))
{
if (cookie.isSessionCookie() || (cookie.expirationDate() <= now))
cookies.removeAll(cookie);
}
@@ -87,7 +89,8 @@ namespace
{
const QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = QNetworkCookieJar::cookiesForUrl(url);
for (const QNetworkCookie &cookie : asConst(QNetworkCookieJar::cookiesForUrl(url))) {
for (const QNetworkCookie &cookie : asConst(QNetworkCookieJar::cookiesForUrl(url)))
{
if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now))
cookies.removeAll(cookie);
}
@@ -99,7 +102,8 @@ namespace
{
const QDateTime now = QDateTime::currentDateTime();
QList<QNetworkCookie> cookies = cookieList;
for (const QNetworkCookie &cookie : cookieList) {
for (const QNetworkCookie &cookie : cookieList)
{
if (!cookie.isSessionCookie() && (cookie.expirationDate() <= now))
cookies.removeAll(cookie);
}
@@ -172,10 +176,12 @@ Net::DownloadHandler *Net::DownloadManager::download(const DownloadRequest &down
m_waitingJobs[id].removeOne(downloadHandler);
});
if (isSequentialService && m_busyServices.contains(id)) {
if (isSequentialService && m_busyServices.contains(id))
{
m_waitingJobs[id].enqueue(downloadHandler);
}
else {
else
{
qDebug("Downloading %s...", qUtf8Printable(downloadRequest.url()));
if (isSequentialService)
m_busyServices.insert(id);
@@ -230,27 +236,32 @@ void Net::DownloadManager::applyProxySettings()
const ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration();
QNetworkProxy proxy;
if (!proxyManager->isProxyOnlyForTorrents() && (proxyConfig.type != ProxyType::None)) {
if (!proxyManager->isProxyOnlyForTorrents() && (proxyConfig.type != ProxyType::None))
{
// Proxy enabled
proxy.setHostName(proxyConfig.ip);
proxy.setPort(proxyConfig.port);
// Default proxy type is HTTP, we must change if it is SOCKS5
if ((proxyConfig.type == ProxyType::SOCKS5) || (proxyConfig.type == ProxyType::SOCKS5_PW)) {
if ((proxyConfig.type == ProxyType::SOCKS5) || (proxyConfig.type == ProxyType::SOCKS5_PW))
{
qDebug() << Q_FUNC_INFO << "using SOCKS proxy";
proxy.setType(QNetworkProxy::Socks5Proxy);
}
else {
else
{
qDebug() << Q_FUNC_INFO << "using HTTP proxy";
proxy.setType(QNetworkProxy::HttpProxy);
}
// Authentication?
if (proxyManager->isAuthenticationRequired()) {
if (proxyManager->isAuthenticationRequired())
{
qDebug("Proxy requires authentication, authenticating...");
proxy.setUser(proxyConfig.username);
proxy.setPassword(proxyConfig.password);
}
}
else {
else
{
proxy.setType(QNetworkProxy::NoProxy);
}
@@ -264,7 +275,8 @@ void Net::DownloadManager::handleReplyFinished(const QNetworkReply *reply)
// in the case when the redirection occurred.
const ServiceID id = ServiceID::fromURL(reply->request().url());
const auto waitingJobsIter = m_waitingJobs.find(id);
if ((waitingJobsIter == m_waitingJobs.end()) || waitingJobsIter.value().isEmpty()) {
if ((waitingJobsIter == m_waitingJobs.end()) || waitingJobsIter.value().isEmpty())
{
// No more waiting jobs for given ServiceID
m_busyServices.remove(id);
return;

View File

@@ -88,26 +88,30 @@ GeoIPDatabase *GeoIPDatabase::load(const QString &filename, QString &error)
{
GeoIPDatabase *db = nullptr;
QFile file(filename);
if (file.size() > MAX_FILE_SIZE) {
if (file.size() > MAX_FILE_SIZE)
{
error = tr("Unsupported database file size.");
return nullptr;
}
if (!file.open(QFile::ReadOnly)) {
if (!file.open(QFile::ReadOnly))
{
error = file.errorString();
return nullptr;
}
db = new GeoIPDatabase(file.size());
if (file.read(reinterpret_cast<char *>(db->m_data), db->m_size) != db->m_size) {
if (file.read(reinterpret_cast<char *>(db->m_data), db->m_size) != db->m_size)
{
error = file.errorString();
delete db;
return nullptr;
}
if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error)) {
if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error))
{
delete db;
return nullptr;
}
@@ -118,7 +122,8 @@ GeoIPDatabase *GeoIPDatabase::load(const QString &filename, QString &error)
GeoIPDatabase *GeoIPDatabase::load(const QByteArray &data, QString &error)
{
GeoIPDatabase *db = nullptr;
if (data.size() > MAX_FILE_SIZE) {
if (data.size() > MAX_FILE_SIZE)
{
error = tr("Unsupported database file size.");
return nullptr;
}
@@ -127,7 +132,8 @@ GeoIPDatabase *GeoIPDatabase::load(const QByteArray &data, QString &error)
memcpy(reinterpret_cast<char *>(db->m_data), data.constData(), db->m_size);
if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error)) {
if (!db->parseMetadata(db->readMetadata(), error) || !db->loadDB(error))
{
delete db;
return nullptr;
}
@@ -161,8 +167,10 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const
const uchar *ptr = m_data;
for (int i = 0; i < 16; ++i) {
for (int j = 0; j < 8; ++j) {
for (int i = 0; i < 16; ++i)
{
for (int j = 0; j < 8; ++j)
{
const bool right = static_cast<bool>((addr[i] >> (7 - j)) & 1);
// Interpret the left/right record as number
if (right)
@@ -173,16 +181,20 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const
memcpy(&idPtr[4 - m_recordBytes], ptr, m_recordBytes);
fromBigEndian(idPtr, 4);
if (id == m_nodeCount) {
if (id == m_nodeCount)
{
return {};
}
if (id > m_nodeCount) {
if (id > m_nodeCount)
{
QString country = m_countries.value(id);
if (country.isEmpty()) {
if (country.isEmpty())
{
const quint32 offset = id - m_nodeCount - sizeof(DATA_SECTION_SEPARATOR);
quint32 tmp = offset + m_indexSize + sizeof(DATA_SECTION_SEPARATOR);
const QVariant val = readDataField(tmp);
if (val.userType() == QMetaType::QVariantHash) {
if (val.userType() == QMetaType::QVariantHash)
{
country = val.toHash()["country"].toHash()["iso_code"].toString();
m_countries[id] = country;
}
@@ -198,18 +210,22 @@ QString GeoIPDatabase::lookup(const QHostAddress &hostAddr) const
}
#define CHECK_METADATA_REQ(key, type) \
if (!metadata.contains(#key)) { \
if (!metadata.contains(#key)) \
{ \
error = errMsgNotFound.arg(#key); \
return false; \
} \
if (metadata.value(#key).userType() != QMetaType::type) { \
if (metadata.value(#key).userType() != QMetaType::type) \
{ \
error = errMsgInvalid.arg(#key); \
return false; \
}
#define CHECK_METADATA_OPT(key, type) \
if (metadata.contains(#key)) { \
if (metadata.value(#key).userType() != QMetaType::type) { \
if (metadata.contains(#key)) \
{ \
if (metadata.value(#key).userType() != QMetaType::type) \
{ \
error = errMsgInvalid.arg(#key); \
return false; \
} \
@@ -226,21 +242,24 @@ bool GeoIPDatabase::parseMetadata(const QVariantHash &metadata, QString &error)
CHECK_METADATA_REQ(binary_format_minor_version, UShort);
const uint versionMajor = metadata.value("binary_format_major_version").toUInt();
const uint versionMinor = metadata.value("binary_format_minor_version").toUInt();
if (versionMajor != 2) {
if (versionMajor != 2)
{
error = tr("Unsupported database version: %1.%2").arg(versionMajor).arg(versionMinor);
return false;
}
CHECK_METADATA_REQ(ip_version, UShort);
m_ipVersion = metadata.value("ip_version").value<quint16>();
if (m_ipVersion != 6) {
if (m_ipVersion != 6)
{
error = tr("Unsupported IP version: %1").arg(m_ipVersion);
return false;
}
CHECK_METADATA_REQ(record_size, UShort);
m_recordSize = metadata.value("record_size").value<quint16>();
if (m_recordSize != 24) {
if (m_recordSize != 24)
{
error = tr("Unsupported record size: %1").arg(m_recordSize);
return false;
}
@@ -270,7 +289,8 @@ bool GeoIPDatabase::loadDB(QString &error) const
const int nodeSize = m_recordSize / 4; // in bytes
const int indexSize = m_nodeCount * nodeSize;
if ((m_size < (indexSize + sizeof(DATA_SECTION_SEPARATOR)))
|| (memcmp(m_data + indexSize, DATA_SECTION_SEPARATOR, sizeof(DATA_SECTION_SEPARATOR)) != 0)) {
|| (memcmp(m_data + indexSize, DATA_SECTION_SEPARATOR, sizeof(DATA_SECTION_SEPARATOR)) != 0))
{
error = tr("Database corrupted: no data section found.");
return false;
}
@@ -282,14 +302,16 @@ QVariantHash GeoIPDatabase::readMetadata() const
{
const char *ptr = reinterpret_cast<const char *>(m_data);
quint32 size = m_size;
if (m_size > MAX_METADATA_SIZE) {
if (m_size > MAX_METADATA_SIZE)
{
ptr += m_size - MAX_METADATA_SIZE;
size = MAX_METADATA_SIZE;
}
const QByteArray data = QByteArray::fromRawData(ptr, size);
int index = data.lastIndexOf(METADATA_BEGIN_MARK);
if (index >= 0) {
if (index >= 0)
{
if (m_size > MAX_METADATA_SIZE)
index += (m_size - MAX_METADATA_SIZE); // from begin of all data
auto offset = static_cast<quint32>(index + strlen(METADATA_BEGIN_MARK));
@@ -309,7 +331,8 @@ QVariant GeoIPDatabase::readDataField(quint32 &offset) const
quint32 locOffset = offset;
bool usePointer = false;
if (descr.fieldType == DataType::Pointer) {
if (descr.fieldType == DataType::Pointer)
{
usePointer = true;
// convert offset from data section to global
locOffset = descr.offset + (m_nodeCount * m_recordSize / 4) + sizeof(DATA_SECTION_SEPARATOR);
@@ -318,7 +341,8 @@ QVariant GeoIPDatabase::readDataField(quint32 &offset) const
}
QVariant fieldValue;
switch (descr.fieldType) {
switch (descr.fieldType)
{
case DataType::Pointer:
qDebug() << "* Illegal Pointer using";
break;
@@ -388,7 +412,8 @@ bool GeoIPDatabase::readDataFieldDescriptor(quint32 &offset, DataFieldDescriptor
if (availSize < 1) return false;
out.fieldType = static_cast<DataType>((dataPtr[0] & 0xE0) >> 5);
if (out.fieldType == DataType::Pointer) {
if (out.fieldType == DataType::Pointer)
{
const int size = ((dataPtr[0] & 0x18) >> 3);
if (availSize < (size + 2)) return false;
@@ -406,28 +431,34 @@ bool GeoIPDatabase::readDataFieldDescriptor(quint32 &offset, DataFieldDescriptor
}
out.fieldSize = dataPtr[0] & 0x1F;
if (out.fieldSize <= 28) {
if (out.fieldType == DataType::Unknown) {
if (out.fieldSize <= 28)
{
if (out.fieldType == DataType::Unknown)
{
out.fieldType = static_cast<DataType>(dataPtr[1] + 7);
if ((out.fieldType <= DataType::Map) || (out.fieldType > DataType::Float) || (availSize < 3))
return false;
offset += 2;
}
else {
else
{
offset += 1;
}
}
else if (out.fieldSize == 29) {
else if (out.fieldSize == 29)
{
if (availSize < 2) return false;
out.fieldSize = dataPtr[1] + 29;
offset += 2;
}
else if (out.fieldSize == 30) {
else if (out.fieldSize == 30)
{
if (availSize < 3) return false;
out.fieldSize = (dataPtr[1] << 8) + dataPtr[2] + 285;
offset += 3;
}
else if (out.fieldSize == 31) {
else if (out.fieldSize == 31)
{
if (availSize < 4) return false;
out.fieldSize = (dataPtr[1] << 16) + (dataPtr[2] << 8) + dataPtr[3] + 65821;
offset += 4;
@@ -450,7 +481,8 @@ QVariant GeoIPDatabase::readMapValue(quint32 &offset, const quint32 count) const
{
QVariantHash map;
for (quint32 i = 0; i < count; ++i) {
for (quint32 i = 0; i < count; ++i)
{
QVariant field = readDataField(offset);
if (field.userType() != QMetaType::QString)
return {};
@@ -470,7 +502,8 @@ QVariant GeoIPDatabase::readArrayValue(quint32 &offset, const quint32 count) con
{
QVariantList array;
for (quint32 i = 0; i < count; ++i) {
for (quint32 i = 0; i < count; ++i)
{
const QVariant field = readDataField(offset);
if (field.userType() == QVariant::Invalid)
return {};

View File

@@ -74,7 +74,8 @@ private:
const uchar *const data = m_data + offset;
const quint32 availSize = m_size - offset;
if ((len > 0) && (len <= sizeof(T) && (availSize >= len))) {
if ((len > 0) && (len <= sizeof(T) && (availSize >= len)))
{
// copy input data to last 'len' bytes of 'value'
uchar *dst = reinterpret_cast<uchar *>(&value) + (sizeof(T) - len);
memcpy(dst, data, len);

View File

@@ -140,7 +140,8 @@ QString GeoIPManager::lookup(const QHostAddress &hostAddr) const
QString GeoIPManager::CountryName(const QString &countryISOCode)
{
static const QHash<QString, QString> countries = {
static const QHash<QString, QString> countries =
{
// ISO 3166-1 alpha-2 codes
// http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements_txt-temp.htm
@@ -404,12 +405,15 @@ QString GeoIPManager::CountryName(const QString &countryISOCode)
void GeoIPManager::configure()
{
const bool enabled = Preferences::instance()->resolvePeerCountries();
if (m_enabled != enabled) {
if (m_enabled != enabled)
{
m_enabled = enabled;
if (m_enabled && !m_geoIPDatabase) {
if (m_enabled && !m_geoIPDatabase)
{
loadDatabase();
}
else if (!m_enabled) {
else if (!m_enabled)
{
delete m_geoIPDatabase;
m_geoIPDatabase = nullptr;
}
@@ -418,22 +422,26 @@ void GeoIPManager::configure()
void GeoIPManager::downloadFinished(const DownloadResult &result)
{
if (result.status != DownloadStatus::Success) {
if (result.status != DownloadStatus::Success)
{
LogMsg(tr("Couldn't download IP geolocation database file. Reason: %1").arg(result.errorString), Log::WARNING);
return;
}
bool ok = false;
const QByteArray data = Utils::Gzip::decompress(result.data, &ok);
if (!ok) {
if (!ok)
{
LogMsg(tr("Could not decompress IP geolocation database file."), Log::WARNING);
return;
}
QString error;
GeoIPDatabase *geoIPDatabase = GeoIPDatabase::load(data, error);
if (geoIPDatabase) {
if (!m_geoIPDatabase || (geoIPDatabase->buildEpoch() > m_geoIPDatabase->buildEpoch())) {
if (geoIPDatabase)
{
if (!m_geoIPDatabase || (geoIPDatabase->buildEpoch() > m_geoIPDatabase->buildEpoch()))
{
delete m_geoIPDatabase;
m_geoIPDatabase = geoIPDatabase;
LogMsg(tr("IP geolocation database loaded. Type: %1. Build time: %2.")
@@ -449,11 +457,13 @@ void GeoIPManager::downloadFinished(const DownloadResult &result)
else
LogMsg(tr("Successfully updated IP geolocation database."), Log::INFO);
}
else {
else
{
delete geoIPDatabase;
}
}
else {
else
{
LogMsg(tr("Couldn't load IP geolocation database. Reason: %1").arg(error), Log::WARNING);
}
}

View File

@@ -100,7 +100,8 @@ ProxyConfiguration ProxyConfigurationManager::proxyConfiguration() const
void ProxyConfigurationManager::setProxyConfiguration(const ProxyConfiguration &config)
{
if (config != m_config) {
if (config != m_config)
{
m_config = config;
settings()->storeValue(KEY_TYPE, static_cast<int>(config.type));
settings()->storeValue(KEY_IP, config.ip);
@@ -120,7 +121,8 @@ bool ProxyConfigurationManager::isProxyOnlyForTorrents() const
void ProxyConfigurationManager::setProxyOnlyForTorrents(bool onlyForTorrents)
{
if (m_isProxyOnlyForTorrents != onlyForTorrents) {
if (m_isProxyOnlyForTorrents != onlyForTorrents)
{
settings()->storeValue(KEY_ONLY_FOR_TORRENTS, onlyForTorrents);
m_isProxyOnlyForTorrents = onlyForTorrents;
}
@@ -136,8 +138,10 @@ void ProxyConfigurationManager::configureProxy()
{
// Define environment variables for urllib in search engine plugins
QString proxyStrHTTP, proxyStrSOCK;
if (!m_isProxyOnlyForTorrents) {
switch (m_config.type) {
if (!m_isProxyOnlyForTorrents)
{
switch (m_config.type)
{
case ProxyType::HTTP_PW:
proxyStrHTTP = QString::fromLatin1("http://%1:%2@%3:%4").arg(m_config.username
, m_config.password, m_config.ip, QString::number(m_config.port));

View File

@@ -60,7 +60,8 @@ ReverseResolution::~ReverseResolution()
void ReverseResolution::resolve(const QHostAddress &ip)
{
const QString *hostname = m_cache.object(ip);
if (hostname) {
if (hostname)
{
emit ipResolved(ip, *hostname);
return;
}
@@ -74,7 +75,8 @@ void ReverseResolution::hostResolved(const QHostInfo &host)
{
const QHostAddress ip = m_lookups.take(host.lookupId());
if (host.error() != QHostInfo::NoError) {
if (host.error() != QHostInfo::NoError)
{
emit ipResolved(ip, {});
return;
}

View File

@@ -67,7 +67,8 @@ namespace
// ascii characters 0x36 ("6") and 0x5c ("\") are selected because they have large
// Hamming distance (http://en.wikipedia.org/wiki/Hamming_distance)
for (int i = 0; i < key.length(); ++i) {
for (int i = 0; i < key.length(); ++i)
{
innerPadding[i] = innerPadding[i] ^ key.at(i); // XOR operation between every byte in key and innerpadding, of key length
outerPadding[i] = outerPadding[i] ^ key.at(i); // XOR operation between every byte in key and outerpadding, of key length
}
@@ -100,7 +101,8 @@ Smtp::Smtp(QObject *parent)
{
static bool needToRegisterMetaType = true;
if (needToRegisterMetaType) {
if (needToRegisterMetaType)
{
qRegisterMetaType<QAbstractSocket::SocketError>();
needToRegisterMetaType = false;
}
@@ -153,18 +155,21 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje
m_from = from;
m_rcpt = to;
// Authentication
if (pref->getMailNotificationSMTPAuth()) {
if (pref->getMailNotificationSMTPAuth())
{
m_username = pref->getMailNotificationSMTPUsername();
m_password = pref->getMailNotificationSMTPPassword();
}
// Connect to SMTP server
#ifndef QT_NO_OPENSSL
if (pref->getMailNotificationSMTPSSL()) {
if (pref->getMailNotificationSMTPSSL())
{
m_socket->connectToHostEncrypted(pref->getMailNotificationSMTP(), DEFAULT_PORT_SSL);
m_useSsl = true;
}
else {
else
{
#endif
m_socket->connectToHost(pref->getMailNotificationSMTP(), DEFAULT_PORT);
m_useSsl = false;
@@ -178,7 +183,8 @@ void Smtp::readyRead()
qDebug() << Q_FUNC_INFO;
// SMTP is line-oriented
m_buffer += m_socket->readAll();
while (true) {
while (true)
{
const int pos = m_buffer.indexOf("\r\n");
if (pos < 0) return; // Loop exit condition
const QByteArray line = m_buffer.left(pos);
@@ -187,9 +193,11 @@ void Smtp::readyRead()
// Extract response code
const QByteArray code = line.left(3);
switch (m_state) {
switch (m_state)
{
case Init:
if (code[0] == '2') {
if (code[0] == '2')
{
// The server may send a multiline greeting/INIT/220 response.
// We wait until it finishes.
if (line[3] != ' ')
@@ -197,7 +205,8 @@ void Smtp::readyRead()
// Connection was successful
ehlo();
}
else {
else
{
logError(QLatin1String("Connection failed, unrecognized reply: ") + line);
m_state = Close;
}
@@ -209,11 +218,13 @@ void Smtp::readyRead()
break;
#ifndef QT_NO_OPENSSL
case StartTLSSent:
if (code == "220") {
if (code == "220")
{
m_socket->startClientEncryption();
ehlo();
}
else {
else
{
authenticate();
}
break;
@@ -226,59 +237,69 @@ void Smtp::readyRead()
break;
case AuthSent:
case Authenticated:
if (code[0] == '2') {
if (code[0] == '2')
{
qDebug() << "Sending <mail from>...";
m_socket->write("mail from:<" + m_from.toLatin1() + ">\r\n");
m_socket->flush();
m_state = Rcpt;
}
else {
else
{
// Authentication failed!
logError(QLatin1String("Authentication failed, msg: ") + line);
m_state = Close;
}
break;
case Rcpt:
if (code[0] == '2') {
if (code[0] == '2')
{
m_socket->write("rcpt to:<" + m_rcpt.toLatin1() + ">\r\n");
m_socket->flush();
m_state = Data;
}
else {
else
{
logError(QLatin1String("<mail from> was rejected by server, msg: ") + line);
m_state = Close;
}
break;
case Data:
if (code[0] == '2') {
if (code[0] == '2')
{
m_socket->write("data\r\n");
m_socket->flush();
m_state = Body;
}
else {
else
{
logError(QLatin1String("<Rcpt to> was rejected by server, msg: ") + line);
m_state = Close;
}
break;
case Body:
if (code[0] == '3') {
if (code[0] == '3')
{
m_socket->write(m_message + "\r\n.\r\n");
m_socket->flush();
m_state = Quit;
}
else {
else
{
logError(QLatin1String("<data> was rejected by server, msg: ") + line);
m_state = Close;
}
break;
case Quit:
if (code[0] == '2') {
if (code[0] == '2')
{
m_socket->write("QUIT\r\n");
m_socket->flush();
// here, we just close.
m_state = Close;
}
else {
else
{
logError(QLatin1String("Message was rejected by the server, error: ") + line);
m_state = Close;
}
@@ -296,10 +317,13 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons
QByteArray rv = "";
QByteArray line = key.toLatin1() + ": ";
if (!prefix.isEmpty()) line += prefix;
if (!value.contains("=?") && latin1->canEncode(value)) {
if (!value.contains("=?") && latin1->canEncode(value))
{
bool firstWord = true;
for (const QByteArray &word : asConst(value.toLatin1().split(' '))) {
if (line.size() > 78) {
for (const QByteArray &word : asConst(value.toLatin1().split(' ')))
{
if (line.size() > 78)
{
rv = rv + line + "\r\n";
line.clear();
}
@@ -310,7 +334,8 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons
firstWord = false;
}
}
else {
else
{
// The text cannot be losslessly encoded as Latin-1. Therefore, we
// must use base64 encoding.
const QByteArray utf8 = value.toUtf8();
@@ -318,8 +343,10 @@ QByteArray Smtp::encodeMimeHeader(const QString &key, const QString &value, cons
const QByteArray base64 = utf8.toBase64();
const int ct = base64.length();
line += "=?utf-8?b?";
for (int i = 0; i < ct; i += 4) {
/*if (line.length() > 72) {
for (int i = 0; i < ct; i += 4)
{
/*if (line.length() > 72)
{
rv += line + "?\n\r";
line = " =?utf-8?b?";
}*/
@@ -348,14 +375,17 @@ void Smtp::helo()
void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const QString &line)
{
if (code != "250") {
if (code != "250")
{
// Error
if (m_state == EhloSent) {
if (m_state == EhloSent)
{
// try to send HELO instead of EHLO
qDebug() << "EHLO failed, trying HELO instead...";
helo();
}
else {
else
{
// Both EHLO and HELO failed, chances are this is NOT
// a SMTP server
logError("Both EHLO and HELO failed, msg: " + line);
@@ -364,20 +394,24 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const
return;
}
if (m_state != EhloGreetReceived) {
if (!continued) {
if (m_state != EhloGreetReceived)
{
if (!continued)
{
// greeting only, no extensions
qDebug() << "No extension";
m_state = EhloDone;
}
else {
else
{
// greeting followed by extensions
m_state = EhloGreetReceived;
qDebug() << "EHLO greet received";
return;
}
}
else {
else
{
qDebug() << Q_FUNC_INFO << "Supported extension: " << line.section(' ', 0, 0).toUpper()
<< line.section(' ', 1);
m_extensions[line.section(' ', 0, 0).toUpper()] = line.section(' ', 1);
@@ -387,11 +421,13 @@ void Smtp::parseEhloResponse(const QByteArray &code, const bool continued, const
if (m_state != EhloDone) return;
if (m_extensions.contains("STARTTLS") && m_useSsl) {
if (m_extensions.contains("STARTTLS") && m_useSsl)
{
qDebug() << "STARTTLS";
startTLS();
}
else {
else
{
authenticate();
}
}
@@ -400,7 +436,8 @@ void Smtp::authenticate()
{
qDebug() << Q_FUNC_INFO;
if (!m_extensions.contains("AUTH") ||
m_username.isEmpty() || m_password.isEmpty()) {
m_username.isEmpty() || m_password.isEmpty())
{
// Skip authentication
qDebug() << "Skipping authentication...";
m_state = Authenticated;
@@ -414,19 +451,23 @@ void Smtp::authenticate()
// authentication modes are supported by
// the server
const QStringList auth = m_extensions["AUTH"].toUpper().split(' ', QString::SkipEmptyParts);
if (auth.contains("CRAM-MD5")) {
if (auth.contains("CRAM-MD5"))
{
qDebug() << "Using CRAM-MD5 authentication...";
authCramMD5();
}
else if (auth.contains("PLAIN")) {
else if (auth.contains("PLAIN"))
{
qDebug() << "Using PLAIN authentication...";
authPlain();
}
else if (auth.contains("LOGIN")) {
else if (auth.contains("LOGIN"))
{
qDebug() << "Using LOGIN authentication...";
authLogin();
}
else {
else
{
// Skip authentication
logError("The SMTP server does not seem to support any of the authentications modes "
"we support [CRAM-MD5|PLAIN|LOGIN], skipping authentication, "
@@ -453,13 +494,15 @@ void Smtp::startTLS()
void Smtp::authCramMD5(const QByteArray &challenge)
{
if (m_state != AuthRequestSent) {
if (m_state != AuthRequestSent)
{
m_socket->write("auth cram-md5\r\n");
m_socket->flush();
m_authType = AuthCramMD5;
m_state = AuthRequestSent;
}
else {
else
{
const QByteArray response = m_username.toLatin1() + ' '
+ hmacMD5(m_password.toLatin1(), QByteArray::fromBase64(challenge)).toHex();
m_socket->write(response.toBase64() + "\r\n");
@@ -470,7 +513,8 @@ void Smtp::authCramMD5(const QByteArray &challenge)
void Smtp::authPlain()
{
if (m_state != AuthRequestSent) {
if (m_state != AuthRequestSent)
{
m_authType = AuthPlain;
// Prepare Auth string
QByteArray auth;
@@ -489,18 +533,21 @@ void Smtp::authPlain()
void Smtp::authLogin()
{
if ((m_state != AuthRequestSent) && (m_state != AuthUsernameSent)) {
if ((m_state != AuthRequestSent) && (m_state != AuthUsernameSent))
{
m_socket->write("auth login\r\n");
m_socket->flush();
m_authType = AuthLogin;
m_state = AuthRequestSent;
}
else if (m_state == AuthRequestSent) {
else if (m_state == AuthRequestSent)
{
m_socket->write(m_username.toLatin1().toBase64() + "\r\n");
m_socket->flush();
m_state = AuthUsernameSent;
}
else {
else
{
m_socket->write(m_password.toLatin1().toBase64() + "\r\n");
m_socket->flush();
m_state = AuthSent;