File indexing completed on 2024-05-12 11:54:36
0001 /* 0002 fixhostfilter.cpp 0003 0004 This file is part of the KDE project 0005 SPDX-FileCopyrightText: 2007 Lubos Lunak <llunak@suse.cz> 0006 SPDX-FileCopyrightText: 2010 Dawit Alemayehu <adawit@kde.org> 0007 0008 SPDX-License-Identifier: GPL-2.0-or-later 0009 */ 0010 0011 #include "fixhosturifilter.h" 0012 0013 #include <QHostInfo> 0014 0015 #include <KPluginFactory> 0016 0017 /** 0018 * IMPORTANT: If you change anything here, make sure you run the kurifiltertest 0019 * regression test (this should be included as part of "make test"). 0020 */ 0021 0022 FixHostUriFilter::FixHostUriFilter(QObject *parent, const QVariantList & /*args*/) 0023 : KUriFilterPlugin(QStringLiteral("fixhosturifilter"), parent) 0024 { 0025 } 0026 0027 static bool isHttpUrl(const QString &scheme) 0028 { 0029 /* clang-format off */ 0030 return scheme.compare(QLatin1String("http"), Qt::CaseInsensitive) == 0 0031 || scheme.compare(QLatin1String("https"), Qt::CaseInsensitive) == 0 0032 || scheme.compare(QLatin1String("webdav"), Qt::CaseInsensitive) == 0 0033 || scheme.compare(QLatin1String("webdavs"), Qt::CaseInsensitive) == 0; 0034 /* clang-format on */ 0035 } 0036 0037 static bool hasCandidateHostName(const QString &host) 0038 { 0039 return host.contains(QLatin1Char('.')) && !host.startsWith(QLatin1String("www."), Qt::CaseInsensitive); 0040 } 0041 0042 bool FixHostUriFilter::filterUri(KUriFilterData &data) const 0043 { 0044 QUrl url = data.uri(); 0045 0046 const QString protocol = url.scheme(); 0047 const bool isHttp = isHttpUrl(protocol); 0048 0049 if (isHttp || protocol == data.defaultUrlScheme()) { 0050 const QString host = url.host(); 0051 if (hasCandidateHostName(host) && !isResolvable(host)) { 0052 if (isHttp) { 0053 url.setHost((QLatin1String("www.") + host)); 0054 if (exists(url.host())) { 0055 setFilteredUri(data, url); 0056 setUriType(data, KUriFilterData::NetProtocol); 0057 return true; 0058 } 0059 } 0060 } 0061 } 0062 0063 return false; 0064 } 0065 0066 bool FixHostUriFilter::isResolvable(const QString &host) const 0067 { 0068 // Unlike exists, this function returns true if the lookup timeout out. 0069 QHostInfo info = resolveName(host, 1500); 0070 return info.error() == QHostInfo::NoError || info.error() == QHostInfo::UnknownError; 0071 } 0072 0073 bool FixHostUriFilter::exists(const QString &host) const 0074 { 0075 QHostInfo info = resolveName(host, 1500); 0076 return info.error() == QHostInfo::NoError; 0077 } 0078 0079 K_PLUGIN_CLASS_WITH_JSON(FixHostUriFilter, "fixhosturifilter.json") 0080 0081 #include "fixhosturifilter.moc" 0082 0083 #include "moc_fixhosturifilter.cpp"