aboutsummaryrefslogtreecommitdiff
path: root/src/webengine/urlinterceptor.cpp
blob: 2f3f04f80aa8156e7117531d5c531c4792ac7bb4 (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
/*
 * 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 <QFile>
#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);
    for(const QString &file : hostsD.entryList(QDir::Files)) {
        qDebug("Parsing hosts.d/%s: %i", qUtf8Printable(file), parseHostfile(hostsD.absoluteFilePath(file)));
    }
}

UrlRequestInterceptor::~UrlRequestInterceptor()
{
    for(HostRule *r : m_rules) {
        delete r;
    }
}

void UrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info)
{
//#ifdef QT_DEBUG
//    qDebug("%s -> %s", qUtf8Printable(info.firstPartyUrl().toString()), qUtf8Printable(info.requestUrl().toString()));
//#endif

    for(HostRule *test : m_rules) {
        if(test->shouldBlock(info)) {
            info.block(true);

//#ifdef QT_DEBUG
//            qDebug("blocked on pattern %s", qUtf8Printable(test->pattern()));
//#endif
            return;
        }
    }
}

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()) {
                HostRule *r = new HostRule(line);
                m_rules.push_back(r);
                ++numRules;
            }
        }

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