aboutsummaryrefslogtreecommitdiff
path: root/src/webengine/urlinterceptor.cpp
blob: bb9bb5f8b7e61f9c6770781a10cf36954f189f70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: git://neueland.iserlohn-fortress.net/smolbote.git
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "urlinterceptor.h"
#include <QDir>
#include <QTextStream>

UrlRequestInterceptor::UrlRequestInterceptor(const QString &path, QObject *parent)
    : QWebEngineUrlRequestInterceptor(parent)
{
#ifdef QT_DEBUG
    qDebug("Reading request blocklist: %s", qUtf8Printable(path));
#endif

    QDir hostsD(path);
    const QStringList hostFiles = hostsD.entryList(QDir::Files);
    for(const QString &file : hostFiles) {
        qDebug("Parsing hosts.d/%s: %i", qUtf8Printable(file), parseHostfile(hostsD.absoluteFilePath(file)));
    }

    qDebug("Total number of rules: %i", m_rules.count());
}

UrlRequestInterceptor::~UrlRequestInterceptor()
{
    qDeleteAll(m_rules);
}

void UrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info)
{
    if(m_rules.contains(info.requestUrl().host())) {
        if(m_rules.value(info.requestUrl().host())->isBlocking) {
            info.block(true);
        }
    }
}

int UrlRequestInterceptor::parseHostfile(const QString &filename)
{
    int numRules = 0;
    QFile file(filename);

    // try to open the file
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {

        // with a QTextStream we can read lines without getting linebreaks at the end
        QTextStream out(&file);
        while(!out.atEnd()) {
            const QString &line = out.readLine().trimmed();

            // skip comments and empty lines
            if(!line.startsWith('#') && !line.isEmpty()) {
                // format is <redirect> <host>
                //0.0.0.0 host
                QStringList parts = line.split(' ');
                QString redirect = parts.at(0);
                QString host = parts.at(1);

                if(m_rules.contains(host)) {
                    qWarning("Duplicate rule %s", qUtf8Printable(line));
                }

                if(redirect == "0.0.0.0") {
                    HostRule *rule = new HostRule;
                    rule->isBlocking = true;
                    m_rules.insert(host, rule);

                    ++numRules;
                } else {
                    qDebug("Ignoring rule %s", qUtf8Printable(line));
                }
            }
        }

        // close once we're done with it
        file.close();
    }
    return numRules;
}