aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/reverselookup-worker.js
blob: 946001cf13cf3c79cb0a5d6573cc22e545edc60a (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/*******************************************************************************

    uBlock - a browser extension to block requests.
    Copyright (C) 2015 Raymond Hill

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see {http://www.gnu.org/licenses/}.

    Home: https://github.com/gorhill/uBlock
*/

/* global onmessage, postMessage */

'use strict';

/******************************************************************************/

var listEntries = Object.create(null);

/******************************************************************************/

// Helpers

var reEscape = function(s) {
    return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

var reSpecialChars = /[\*\^\t\v\n]/;

/******************************************************************************/

var fromNetFilter = function(details) {
    var lists = [];

    var compiledFilter = details.compiledFilter;
    var entry, content, pos, c;
    for ( var path in listEntries ) {
        entry = listEntries[path];
        if ( entry === undefined ) {
            continue;
        }
        content = entry.content;
        pos = content.indexOf(compiledFilter);
        if ( pos === -1 ) {
            continue;
        }
        // https://github.com/gorhill/uBlock/issues/835
        // We need an exact match.
        c = content.charAt(pos + compiledFilter.length);
        if ( c !== '' && reSpecialChars.test(c) === false ) {
            continue;
        }
        lists.push({
            title: entry.title,
            supportURL: entry.supportURL
        });
    }

    var response = {};
    response[details.rawFilter] = lists;

    postMessage({
        id: details.id,
        response: response
    });
};

/******************************************************************************/

// Looking up filter lists from a cosmetic filter is a bit more complicated
// than with network filters:
//
// The filter is its raw representation, not its compiled version. This is
// because the cosmetic filtering engine can't translate a live cosmetic
// filter into its compiled version. Reason is I do not want to burden
// cosmetic filtering with the resource overhead of being able to re-compile
// live cosmetic filters. I want the cosmetic filtering code to be left
// completely unaffected by reverse lookup requirements.
//
// Mainly, given a CSS selector and a hostname as context, we will derive
// various versions of compiled filters and see if there are matches. This way
// the whole CPU cost is incurred by the reverse lookup code -- in a worker
// thread, and the cosmetic filtering engine incurs no cost at all.
//
// For this though, the reverse lookup code here needs some knowledge of
// the inners of the cosmetic filtering engine.
// FilterContainer.fromCompiledContent() is our reference code to create
// the various compiled versions.

var fromCosmeticFilter = function(details) {
    var filter = details.rawFilter;
    var exception = filter.lastIndexOf('#@#', 0) === 0;

    filter = exception ? filter.slice(3) : filter.slice(2);

    var candidates = Object.create(null);
    var response = Object.create(null);

    // First step: assuming the filter is generic, find out its compiled
    // representation.
    // Reference: FilterContainer.compileGenericSelector().
    var reStr = '';
    var matches = rePlainSelector.exec(filter);
    if ( matches ) {
        if ( matches[0] === filter ) {          // simple CSS selector
            reStr = reEscape('c\vlg\v' + filter);
        } else {                                // complex CSS selector
            reStr = reEscape('c\vlg+\v' + matches[0] + '\v' + filter);
        }
    } else if ( reHighLow.test(filter) ) {      // [alt] or [title]
        reStr = reEscape('c\vhlg0\v' + filter);
    } else if ( reHighMedium.test(filter) ) {   // [href^="..."]
        reStr = reEscape('c\vhmg0\v') + '[a-z.-]+' + reEscape('\v') + '[a-z]*' + reEscape(filter);
    } else {                                    // all else
        reStr = reEscape('c\vhhg0\v' + filter);
    }
    candidates[details.rawFilter] = new RegExp(reStr + '(?:\\n|$)');

    // Second step: find hostname-based versions.
    // Reference: FilterContainer.compileHostnameSelector().
    var pos;
    var domain = details.domain;
    var hostname = details.hostname;

    if ( hostname !== '' ) {
        for ( ;; ) {
            candidates[hostname + '##' + filter] = new RegExp(
                reEscape('c\vh\v') +
                '\\w+' +
                reEscape('\v' + hostname + '\v' + filter) +
                '(?:\\n|$)'
            );
            // If there is no valid domain, there won't be any other
            // version of this hostname-based filter.
            if ( domain === '' ) {
                break;
            }
            if ( hostname === domain ) {
                break;
            }
            pos = hostname.indexOf('.');
            if ( pos === -1 ) {
                break;
            }
            hostname = hostname.slice(pos + 1);
        }
    }

    // Last step: find entity-based versions.
    // Reference: FilterContainer.compileEntitySelector().
    pos = domain.indexOf('.');
    if ( pos !== -1 ) {
        var entity = domain.slice(0, pos);
        candidates[entity + '.*##' + filter] = new RegExp(
            reEscape('c\ve\v' + entity + '\v' + filter) +
            '(?:\\n|$)'
        );
    }

    var re, path, entry;
    for ( var candidate in candidates ) {
        re = candidates[candidate];
        for ( path in listEntries ) {
            entry = listEntries[path];
            if ( entry === undefined ) {
                continue;
            }
            if ( re.test(entry.content) === false ) {
                continue;
            }
            if ( response[candidate] === undefined ) {
                response[candidate] = [];
            }
            response[candidate].push({
                title: entry.title,
                supportURL: entry.supportURL
            });
        }
    }

    postMessage({
        id: details.id,
        response: response
    });
};

var rePlainSelector = /^([#.][\w-]+)/;
var reHighLow = /^[a-z]*\[(?:alt|title)="[^"]+"\]$/;
var reHighMedium = /^\[href\^="https?:\/\/([^"]{8})[^"]*"\]$/;

/******************************************************************************/

onmessage = function(e) {
    var msg = e.data;

    switch ( msg.what ) {
    case 'resetLists':
        listEntries = Object.create(null);
        break;

    case 'setList':
        listEntries[msg.details.path] = msg.details;
        break;

    case 'fromNetFilter':
        fromNetFilter(msg);
        break;

    case 'fromCosmeticFilter':
        fromCosmeticFilter(msg);
        break;
    }
};

/******************************************************************************/