/* * 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 #include 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 //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; }