File indexing completed on 2024-04-28 03:55:42

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 static bool isHttpUrl(const QString &scheme)
0018 {
0019     /* clang-format off */
0020     return scheme.compare(QLatin1String("http"), Qt::CaseInsensitive) == 0
0021         || scheme.compare(QLatin1String("https"), Qt::CaseInsensitive) == 0
0022         || scheme.compare(QLatin1String("webdav"), Qt::CaseInsensitive) == 0
0023         || scheme.compare(QLatin1String("webdavs"), Qt::CaseInsensitive) == 0;
0024     /* clang-format on */
0025 }
0026 
0027 static bool hasCandidateHostName(const QString &host)
0028 {
0029     return host.contains(QLatin1Char('.')) && !host.startsWith(QLatin1String("www."), Qt::CaseInsensitive);
0030 }
0031 
0032 bool FixHostUriFilter::filterUri(KUriFilterData &data) const
0033 {
0034     QUrl url = data.uri();
0035 
0036     const QString protocol = url.scheme();
0037     const bool isHttp = isHttpUrl(protocol);
0038 
0039     if (isHttp || protocol == data.defaultUrlScheme()) {
0040         const QString host = url.host();
0041         if (hasCandidateHostName(host) && !isResolvable(host)) {
0042             if (isHttp) {
0043                 url.setHost((QLatin1String("www.") + host));
0044                 if (exists(url.host())) {
0045                     setFilteredUri(data, url);
0046                     setUriType(data, KUriFilterData::NetProtocol);
0047                     return true;
0048                 }
0049             }
0050         }
0051     }
0052 
0053     return false;
0054 }
0055 
0056 bool FixHostUriFilter::isResolvable(const QString &host) const
0057 {
0058     // Unlike exists, this function returns true if the lookup timeout out.
0059     QHostInfo info = resolveName(host, 1500);
0060     return info.error() == QHostInfo::NoError || info.error() == QHostInfo::UnknownError;
0061 }
0062 
0063 bool FixHostUriFilter::exists(const QString &host) const
0064 {
0065     QHostInfo info = resolveName(host, 1500);
0066     return info.error() == QHostInfo::NoError;
0067 }
0068 
0069 K_PLUGIN_CLASS_WITH_JSON(FixHostUriFilter, "fixhosturifilter.json")
0070 
0071 #include "fixhosturifilter.moc"
0072 
0073 #include "moc_fixhosturifilter.cpp"