| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "network-web/adblock/adblockmanager.h" |
| 4 | |
| 5 | #include "3rd-party/boolinq/boolinq.h" |
| 6 | #include "exceptions/applicationexception.h" |
| 7 | #include "exceptions/networkexception.h" |
| 8 | #include "miscellaneous/application.h" |
| 9 | #include "miscellaneous/settings.h" |
| 10 | #include "network-web/adblock/adblockdialog.h" |
| 11 | #include "network-web/adblock/adblockicon.h" |
| 12 | #include "network-web/adblock/adblockrequestinfo.h" |
| 13 | #include "network-web/networkfactory.h" |
| 14 | #include "network-web/webfactory.h" |
| 15 | |
| 16 | #if defined(NO_LITE) |
| 17 | #include "network-web/adblock/adblockurlinterceptor.h" |
| 18 | #include "network-web/webengine/networkurlinterceptor.h" |
| 19 | #endif |
| 20 | |
| 21 | #include <QDateTime> |
| 22 | #include <QDir> |
| 23 | #include <QJsonDocument> |
| 24 | #include <QJsonObject> |
| 25 | #include <QMessageBox> |
| 26 | #include <QTimer> |
| 27 | #include <QUrlQuery> |
| 28 | |
| 29 | AdBlockManager::AdBlockManager(QObject* parent) |
| 30 | : QObject(parent), m_loaded(false), m_enabled(false), m_installing(false), |
| 31 | #if defined(NO_LITE) |
| 32 | m_interceptor(new AdBlockUrlInterceptor(this)), |
| 33 | #endif |
| 34 | m_serverProcess(nullptr), m_cacheBlocks({}) { |
| 35 | m_adblockIcon = new AdBlockIcon(this); |
| 36 | m_adblockIcon->setObjectName(QSL("m_adblockIconAction")); |
| 37 | m_unifiedFiltersFile = qApp->userDataFolder() + QDir::separator() + QSL("adblock-unified-filters.txt"); |
| 38 | |
| 39 | connect(qApp->nodejs(), &NodeJs::packageInstalledUpdated, this, &AdBlockManager::onPackageReady); |
| 40 | connect(qApp->nodejs(), &NodeJs::packageError, this, &AdBlockManager::onPackageError); |
| 41 | } |
| 42 | |
| 43 | AdBlockManager::~AdBlockManager() { |
| 44 | killServer(); |
| 45 | } |
| 46 | |
| 47 | BlockingResult AdBlockManager::block(const AdblockRequestInfo& request) { |
| 48 | if (!isEnabled()) { |
| 49 | return {false}; |
| 50 | } |
| 51 | |
| 52 | const QString url_string = request.requestUrl().toEncoded().toLower(); |
| 53 | const QString firstparty_url_string = request.firstPartyUrl().toEncoded().toLower(); |
| 54 | const QString url_scheme = request.requestUrl().scheme().toLower(); |
| 55 | const QPair<QString, QString> url_pair = {firstparty_url_string, url_string}; |
| 56 | const QString url_type = request.resourceType(); |
| 57 | |
| 58 | if (!canRunOnScheme(url_scheme)) { |
| 59 | return {false}; |
| 60 | } |
| 61 | else { |
| 62 | if (m_cacheBlocks.contains(url_pair)) { |
| 63 | qDebugNN << LOGSEC_ADBLOCK << "Found blocking data in cache, URL:" << QUOTE_W_SPACE_DOT(url_pair); |
| 64 | |
| 65 | return m_cacheBlocks.value(url_pair); |
| 66 | } |
| 67 | |
| 68 | if (m_serverProcess != nullptr && m_serverProcess->state() == QProcess::ProcessState::Running) { |
| 69 | try { |
| 70 | auto result = askServerIfBlocked(firstparty_url_string, url_string, url_type); |
| 71 | |
| 72 | m_cacheBlocks.insert(url_pair, result); |
| 73 | |
| 74 | qDebugNN << LOGSEC_ADBLOCK << "Inserted blocking data to cache for:" << QUOTE_W_SPACE_DOT(url_pair); |
| 75 | |
| 76 | return result; |
| 77 | } |
| 78 | catch (const ApplicationException& ex) { |
| 79 | qCriticalNN << LOGSEC_ADBLOCK |
| 80 | << "HTTP error when calling server for blocking rules:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 81 | return {false}; |
| 82 | } |
| 83 | } |
| 84 | else { |
| 85 | return {false}; |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | void AdBlockManager::setEnabled(bool enabled) { |
| 91 | if (enabled == m_enabled) { |
| 92 | return; |
| 93 | } |
| 94 | |
| 95 | if (!m_loaded) { |
| 96 | #if defined(NO_LITE) |
| 97 | qApp->web()->urlIinterceptor()->installUrlInterceptor(m_interceptor); |
| 98 | #endif |
| 99 | m_loaded = true; |
| 100 | } |
| 101 | |
| 102 | m_enabled = enabled; |
| 103 | emit enabledChanged(m_enabled); |
| 104 | |
| 105 | if (m_enabled) { |
| 106 | if (!m_installing) { |
| 107 | m_installing = true; |
| 108 | qApp->nodejs()->installUpdatePackages(this, {{QSL(CLIQZ_ADBLOCKED_PACKAGE), QSL(CLIQZ_ADBLOCKED_VERSION)}}); |
| 109 | } |
| 110 | } |
| 111 | else { |
| 112 | killServer(); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | bool AdBlockManager::isEnabled() const { |
| 117 | return m_enabled; |
| 118 | } |
| 119 | |
| 120 | bool AdBlockManager::canRunOnScheme(const QString& scheme) const { |
| 121 | return !(scheme == QSL("file") || scheme == QSL("qrc") || scheme == QSL("data") || scheme == QSL("abp")); |
| 122 | } |
| 123 | |
| 124 | QString AdBlockManager::elementHidingRulesForDomain(const QUrl& url) const { |
| 125 | if (m_serverProcess != nullptr && m_serverProcess->state() == QProcess::ProcessState::Running) { |
| 126 | try { |
| 127 | auto result = askServerForCosmeticRules(url.toString()); |
| 128 | |
| 129 | return result; |
| 130 | } |
| 131 | catch (const ApplicationException& ex) { |
| 132 | qCriticalNN << LOGSEC_ADBLOCK |
| 133 | << "HTTP error when calling server for cosmetic rules:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 134 | return {}; |
| 135 | } |
| 136 | } |
| 137 | else { |
| 138 | return {}; |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | QStringList AdBlockManager::filterLists() const { |
| 143 | return qApp->settings()->value(GROUP(AdBlock), SETTING(AdBlock::FilterLists)).toStringList(); |
| 144 | } |
| 145 | |
| 146 | void AdBlockManager::setFilterLists(const QStringList& filter_lists) { |
| 147 | qApp->settings()->setValue(GROUP(AdBlock), AdBlock::FilterLists, filter_lists); |
| 148 | } |
| 149 | |
| 150 | QStringList AdBlockManager::customFilters() const { |
| 151 | return qApp->settings()->value(GROUP(AdBlock), SETTING(AdBlock::CustomFilters)).toStringList(); |
| 152 | } |
| 153 | |
| 154 | void AdBlockManager::setCustomFilters(const QStringList& custom_filters) { |
| 155 | qApp->settings()->setValue(GROUP(AdBlock), AdBlock::CustomFilters, custom_filters); |
| 156 | } |
| 157 | |
| 158 | QString AdBlockManager::generateJsForElementHiding(const QString& css) { |
| 159 | QString source = QSL("(function() {" |
| 160 | "var head = document.getElementsByTagName('head')[0];" |
| 161 | "if (!head) return;" |
| 162 | "var css = document.createElement('style');" |
| 163 | "css.setAttribute('type', 'text/css');" |
| 164 | "css.appendChild(document.createTextNode('%1'));" |
| 165 | "head.appendChild(css);" |
| 166 | "})()"); |
| 167 | QString style = css; |
| 168 | |
| 169 | style.replace(QL1S("'"), QL1S("\\'")); |
| 170 | style.replace(QL1S("\n"), QL1S("\\n")); |
| 171 | |
| 172 | return source.arg(style); |
| 173 | } |
| 174 | |
| 175 | void AdBlockManager::showDialog() { |
| 176 | AdBlockDialog(qApp->mainFormWidget()).exec(); |
| 177 | } |
| 178 | |
| 179 | void AdBlockManager::onPackageReady(const QObject* sndr, |
| 180 | const QList<NodeJs::PackageMetadata>& pkgs, |
| 181 | bool already_up_to_date) { |
| 182 | Q_UNUSED(already_up_to_date) |
| 183 | |
| 184 | bool concerns_adblock = boolinq::from(pkgs).any([](const NodeJs::PackageMetadata& pkg) { |
| 185 | return pkg.m_name == QSL(CLIQZ_ADBLOCKED_PACKAGE); |
| 186 | }); |
| 187 | |
| 188 | if (concerns_adblock) { |
| 189 | m_installing = false; |
| 190 | |
| 191 | if (m_enabled) { |
| 192 | try { |
| 193 | updateUnifiedFiltersFileAndStartServer(); |
| 194 | } |
| 195 | catch (const ApplicationException& ex) { |
| 196 | qCriticalNN << LOGSEC_ADBLOCK << "Failed to setup filters and start server:" << QUOTE_W_SPACE_DOT(ex.message()); |
| 197 | |
| 198 | m_enabled = false; |
| 199 | emit enabledChanged(m_enabled, tr("Failed to setup filters and start server: %1.").arg(ex.message())); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | void AdBlockManager::onPackageError(const QObject* sndr, |
| 206 | const QList<NodeJs::PackageMetadata>& pkgs, |
| 207 | const QString& error) { |
| 208 | Q_UNUSED(sndr) |
| 209 | |
| 210 | bool concerns_adblock = boolinq::from(pkgs).any([](const NodeJs::PackageMetadata& pkg) { |
| 211 | return pkg.m_name == QSL(CLIQZ_ADBLOCKED_PACKAGE); |
| 212 | }); |
| 213 | |
| 214 | if (concerns_adblock) { |
| 215 | m_installing = false; |
| 216 | m_enabled = false; |
| 217 | |
| 218 | qCriticalNN << LOGSEC_ADBLOCK << "Needed Node.js packages were not installed:" << QUOTE_W_SPACE_DOT(error); |
| 219 | |
| 220 | emit processTerminated(); |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | void AdBlockManager::onServerProcessFinished(int exit_code, QProcess::ExitStatus exit_status) { |
| 225 | Q_UNUSED(exit_status) |
| 226 | killServer(); |
| 227 | |
| 228 | qCriticalNN << LOGSEC_ADBLOCK << "Process exited with exit code" << QUOTE_W_SPACE(exit_code) |
| 229 | << "so check application log for more details."; |
| 230 | |
| 231 | m_enabled = false; |
| 232 | emit processTerminated(); |
| 233 | } |
| 234 | |
| 235 | BlockingResult AdBlockManager::askServerIfBlocked(const QString& fp_url, |
| 236 | const QString& url, |
| 237 | const QString& url_type) const { |
| 238 | QJsonObject req_obj; |
| 239 | QByteArray out; |
| 240 | QElapsedTimer tmr; |
| 241 | |
| 242 | req_obj[QSL("fp_url")] = fp_url; |
| 243 | req_obj[QSL("url")] = url; |
| 244 | req_obj[QSL("url_type")] = url_type, req_obj[QSL("filter")] = true; |
| 245 | |
| 246 | tmr.start(); |
| 247 | |
| 248 | auto network_res = |
| 249 | NetworkFactory::performNetworkOperation(QSL("http://%1:%2") |
| 250 | .arg(QHostAddress(QHostAddress::SpecialAddress::LocalHost).toString(), |
| 251 | QString::number(ADBLOCK_SERVER_PORT)), |
| 252 | 500, |
| 253 | QJsonDocument(req_obj).toJson(), |
| 254 | out, |
| 255 | QNetworkAccessManager::Operation::PostOperation, |
| 256 | {{QSL(HTTP_HEADERS_CONTENT_TYPE).toLocal8Bit(), |
| 257 | QSL("application/json").toLocal8Bit()}}); |
| 258 | |
| 259 | if (network_res.m_networkError == QNetworkReply::NetworkError::NoError) { |
| 260 | qDebugNN << LOGSEC_ADBLOCK << "Query for blocking info to server took " << tmr.elapsed() << " ms."; |
| 261 | |
| 262 | QJsonObject out_obj = QJsonDocument::fromJson(out).object(); |
| 263 | bool blocking = out_obj[QSL("filter")].toObject()[QSL("match")].toBool(); |
| 264 | |
| 265 | return {blocking, |
| 266 | blocking ? out_obj[QSL("filter")].toObject()[QSL("filter")].toObject()[QSL("filter")].toString() |
| 267 | : QString()}; |
| 268 | } |
| 269 | else { |
| 270 | throw NetworkException(network_res.m_networkError); |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | QString AdBlockManager::askServerForCosmeticRules(const QString& url) const { |
| 275 | QJsonObject req_obj; |
| 276 | QByteArray out; |
| 277 | QElapsedTimer tmr; |
| 278 | |
| 279 | req_obj[QSL("url")] = url; |
| 280 | req_obj[QSL("cosmetic")] = true; |
| 281 | |
| 282 | tmr.start(); |
| 283 | |
| 284 | auto network_res = |
| 285 | NetworkFactory::performNetworkOperation(QSL("http://%1:%2") |
| 286 | .arg(QHostAddress(QHostAddress::SpecialAddress::LocalHost).toString(), |
| 287 | QString::number(ADBLOCK_SERVER_PORT)), |
| 288 | 500, |
| 289 | QJsonDocument(req_obj).toJson(), |
| 290 | out, |
| 291 | QNetworkAccessManager::Operation::PostOperation, |
| 292 | {{QSL(HTTP_HEADERS_CONTENT_TYPE).toLocal8Bit(), |
| 293 | QSL("application/json").toLocal8Bit()}}); |
| 294 | |
| 295 | if (network_res.m_networkError == QNetworkReply::NetworkError::NoError) { |
| 296 | qDebugNN << LOGSEC_ADBLOCK << "Query for cosmetic rules to server took " << tmr.elapsed() << " ms."; |
| 297 | |
| 298 | QJsonObject out_obj = QJsonDocument::fromJson(out).object(); |
| 299 | |
| 300 | return out_obj[QSL("cosmetic")].toObject()[QSL("styles")].toString(); |
| 301 | } |
| 302 | else { |
| 303 | throw NetworkException(network_res.m_networkError); |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | QProcess* AdBlockManager::startServer(int port) { |
| 308 | QString temp_server = |
| 309 | QDir::toNativeSeparators(IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation)) + |
| 310 | QDir::separator() + QSL(ADBLOCK_SERVER_FILE); |
| 311 | |
| 312 | if (!IOFactory::copyFile(QSL(":/scripts/adblock/") + QSL(ADBLOCK_SERVER_FILE), temp_server)) { |
| 313 | qWarningNN << LOGSEC_ADBLOCK << "Failed to copy server file to TEMP."; |
| 314 | } |
| 315 | |
| 316 | QProcess* proc = new QProcess(this); |
| 317 | |
| 318 | proc->setProcessChannelMode(QProcess::ProcessChannelMode::ForwardedErrorChannel); |
| 319 | |
| 320 | connect(proc, |
| 321 | QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), |
| 322 | this, |
| 323 | &AdBlockManager::onServerProcessFinished); |
| 324 | |
| 325 | qApp->nodejs()->runScript(proc, |
| 326 | QDir::toNativeSeparators(temp_server), |
| 327 | {QString::number(port), QDir::toNativeSeparators(m_unifiedFiltersFile)}); |
| 328 | |
| 329 | qDebugNN << LOGSEC_ADBLOCK << "Attempting to start AdBlock server."; |
| 330 | return proc; |
| 331 | } |
| 332 | |
| 333 | void AdBlockManager::killServer() { |
| 334 | m_cacheBlocks.clear(); |
| 335 | |
| 336 | if (m_serverProcess != nullptr) { |
| 337 | disconnect(m_serverProcess, |
| 338 | QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), |
| 339 | this, |
| 340 | &AdBlockManager::onServerProcessFinished); |
| 341 | |
| 342 | if (m_serverProcess->state() == QProcess::ProcessState::Running) { |
| 343 | m_serverProcess->kill(); |
| 344 | } |
| 345 | |
| 346 | m_serverProcess->deleteLater(); |
| 347 | m_serverProcess = nullptr; |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | void AdBlockManager::updateUnifiedFilters() { |
| 352 | if (QFile::exists(m_unifiedFiltersFile)) { |
| 353 | QFile::remove(m_unifiedFiltersFile); |
| 354 | } |
| 355 | |
| 356 | QString unified_contents; |
| 357 | auto filter_lists = filterLists(); |
| 358 | |
| 359 | // Download filters one by one and append. |
| 360 | for (const QString& filter_list_url : std::as_const(filter_lists)) { |
| 361 | if (filter_list_url.simplified().isEmpty()) { |
| 362 | continue; |
| 363 | } |
| 364 | |
| 365 | QByteArray out; |
| 366 | auto res = NetworkFactory::performNetworkOperation(filter_list_url, |
| 367 | 4000, |
| 368 | {}, |
| 369 | out, |
| 370 | QNetworkAccessManager::Operation::GetOperation); |
| 371 | |
| 372 | if (res.m_networkError == QNetworkReply::NetworkError::NoError) { |
| 373 | unified_contents = unified_contents.append(QString::fromUtf8(out)); |
| 374 | unified_contents = unified_contents.append('\n'); |
| 375 | |
| 376 | qDebugNN << LOGSEC_ADBLOCK << "Downloaded filter list from" << QUOTE_W_SPACE_DOT(filter_list_url); |
| 377 | } |
| 378 | else { |
| 379 | throw NetworkException(res.m_networkError, tr("failed to download filter list '%1'").arg(filter_list_url)); |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | unified_contents = unified_contents.append(customFilters().join(QSL("\n"))); |
| 384 | |
| 385 | // Save. |
| 386 | m_unifiedFiltersFile = IOFactory::getSystemFolder(QStandardPaths::StandardLocation::TempLocation) + |
| 387 | QDir::separator() + QSL("adblock.filters"); |
| 388 | |
| 389 | IOFactory::writeFile(m_unifiedFiltersFile, unified_contents.toUtf8()); |
| 390 | } |
| 391 | |
| 392 | void AdBlockManager::updateUnifiedFiltersFileAndStartServer() { |
| 393 | killServer(); |
| 394 | updateUnifiedFilters(); |
| 395 | |
| 396 | if (m_enabled) { |
| 397 | auto custom_port = qApp->customAdblockPort(); |
| 398 | |
| 399 | m_serverProcess = startServer(custom_port > 0 ? custom_port : ADBLOCK_SERVER_PORT); |
| 400 | } |
| 401 | } |