1 | /* |
2 | fixhostfilter.cpp |
3 | |
4 | This file is part of the KDE project |
5 | SPDX-FileCopyrightText: 2007 Lubos Lunak <llunak@suse.cz> |
6 | SPDX-FileCopyrightText: 2010 Dawit Alemayehu <adawit@kde.org> |
7 | |
8 | SPDX-License-Identifier: GPL-2.0-or-later |
9 | */ |
10 | |
11 | #include "fixhosturifilter.h" |
12 | |
13 | #include <QHostInfo> |
14 | |
15 | #include <KPluginFactory> |
16 | |
17 | static bool isHttpUrl(const QString &scheme) |
18 | { |
19 | /* clang-format off */ |
20 | return scheme.compare(other: QLatin1String("http" ), cs: Qt::CaseInsensitive) == 0 |
21 | || scheme.compare(other: QLatin1String("https" ), cs: Qt::CaseInsensitive) == 0 |
22 | || scheme.compare(other: QLatin1String("webdav" ), cs: Qt::CaseInsensitive) == 0 |
23 | || scheme.compare(other: QLatin1String("webdavs" ), cs: Qt::CaseInsensitive) == 0; |
24 | /* clang-format on */ |
25 | } |
26 | |
27 | static bool hasCandidateHostName(const QString &host) |
28 | { |
29 | return host.contains(c: QLatin1Char('.')) && !host.startsWith(s: QLatin1String("www." ), cs: Qt::CaseInsensitive); |
30 | } |
31 | |
32 | bool FixHostUriFilter::filterUri(KUriFilterData &data) const |
33 | { |
34 | QUrl url = data.uri(); |
35 | |
36 | const QString protocol = url.scheme(); |
37 | const bool isHttp = isHttpUrl(scheme: protocol); |
38 | |
39 | if (isHttp || protocol == data.defaultUrlScheme()) { |
40 | const QString host = url.host(); |
41 | if (hasCandidateHostName(host) && !isResolvable(host)) { |
42 | if (isHttp) { |
43 | url.setHost(host: (QLatin1String("www." ) + host)); |
44 | if (exists(host: url.host())) { |
45 | setFilteredUri(data, uri: url); |
46 | setUriType(data, type: KUriFilterData::NetProtocol); |
47 | return true; |
48 | } |
49 | } |
50 | } |
51 | } |
52 | |
53 | return false; |
54 | } |
55 | |
56 | bool FixHostUriFilter::isResolvable(const QString &host) const |
57 | { |
58 | // Unlike exists, this function returns true if the lookup timeout out. |
59 | QHostInfo info = resolveName(hostname: host, timeout: 1500); |
60 | return info.error() == QHostInfo::NoError || info.error() == QHostInfo::UnknownError; |
61 | } |
62 | |
63 | bool FixHostUriFilter::exists(const QString &host) const |
64 | { |
65 | QHostInfo info = resolveName(hostname: host, timeout: 1500); |
66 | return info.error() == QHostInfo::NoError; |
67 | } |
68 | |
69 | K_PLUGIN_CLASS_WITH_JSON(FixHostUriFilter, "fixhosturifilter.json" ) |
70 | |
71 | #include "fixhosturifilter.moc" |
72 | |
73 | #include "moc_fixhosturifilter.cpp" |
74 | |