summaryrefslogtreecommitdiffstats
path: root/platform/nodejs/index.js
blob: 1d39a7d11292e82978d634051323eec566369c3f (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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*******************************************************************************

    uBlock Origin - a comprehensive, efficient content blocker
    Copyright (C) 2014-present 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
*/

/* globals WebAssembly */

'use strict';

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

import { createRequire } from 'module';

import { readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import { domainToASCII, fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

import publicSuffixList from './lib/publicsuffixlist/publicsuffixlist.js';

import snfe from './js/static-net-filtering.js';
import { FilteringContext } from './js/filtering-context.js';
import { LineIterator } from './js/text-utils.js';
import * as sfp from './js/static-filtering-parser.js';

import {
    CompiledListReader,
    CompiledListWriter,
} from './js/static-filtering-io.js';

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

function loadJSON(path) {
    return JSON.parse(readFileSync(resolve(__dirname, path), 'utf8'));
}

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

async function enableWASM() {
    const wasmModuleFetcher = function(path) {
        const require = createRequire(import.meta.url); // jshint ignore:line
        const wasm = new Uint8Array(require(`${path}.wasm.json`));
        return WebAssembly.compile(wasm);
    };
    try {
        const results = await Promise.all([
            publicSuffixList.enableWASM(wasmModuleFetcher, './lib/publicsuffixlist/wasm/'),
            snfe.enableWASM(wasmModuleFetcher, './js/wasm/'),
        ]);
        return results.every(a => a === true);
    } catch(reason) {
        console.log(reason);
    }
    return false;
}

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

function pslInit(raw) {
    if ( typeof raw === 'string' && raw.trim() !== '' ) {
        publicSuffixList.parse(raw, domainToASCII);
        return publicSuffixList;
    }

    // Use serialized version if available
    let serialized = null;
    try {
        // Use loadJSON() because require() would keep the string in memory.
        serialized = loadJSON('build/publicsuffixlist.json');
    } catch (error) {
        if ( process.env.npm_lifecycle_event !== 'build' ) {
            // This should never happen except during package building.
            console.error(error);
        }
    }
    if ( serialized !== null ) {
        publicSuffixList.fromSelfie(serialized);
        return publicSuffixList;
    }

    raw = readFileSync(
        resolve(__dirname, './assets/thirdparties/publicsuffix.org/list/effective_tld_names.dat'),
        'utf8'
    );
    if ( typeof raw !== 'string' || raw.trim() === '' ) {
        console.error('Unable to populate public suffix list');
        return;
    }
    publicSuffixList.parse(raw, domainToASCII);
    return publicSuffixList;
}

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

function compileList({ name, raw }, compiler, writer, options = {}) {
    const lineIter = new LineIterator(raw);
    const events = Array.isArray(options.events) ? options.events : undefined;

    if ( name ) {
        writer.properties.set('name', name);
    }

    const parser = new sfp.AstFilterParser({
        maxTokenLength: snfe.MAX_TOKEN_LENGTH,
    });

    while ( lineIter.eot() === false ) {
        let line = lineIter.next();
        while ( line.endsWith(' \\') ) {
            if ( lineIter.peek(4) !== '    ' ) { break; }
            line = line.slice(0, -2).trim() + lineIter.next().trim();
        }
        parser.parse(line);
        if ( parser.isFilter() === false ) { continue; }
        if ( parser.isNetworkFilter() === false ) { continue; }
        if ( compiler.compile(parser, writer) ) { continue; }
        if ( compiler.error !== undefined && events !== undefined ) {
            options.events.push({
                type: 'error',
                text: compiler.error
            });
        }
    }

    return writer.toString();
}

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

async function useLists(lists, options = {}) {
    if ( useLists.promise !== null ) {
        throw new Error('Pending useLists() operation');
    }

    // Remove all filters
    snfe.reset();

    if ( Array.isArray(lists) === false || lists.length === 0 ) {
        return;
    }

    let compiler = null;

    const consumeList = list => {
        let { compiled } = list;
        if ( typeof compiled !== 'string' || compiled === '' ) {
            const writer = new CompiledListWriter();
            if ( compiler === null ) {
                compiler = snfe.createCompiler();
            }
            compiled = compileList(list, compiler, writer, options);
        }
        snfe.fromCompiled(new CompiledListReader(compiled));
    };

    // Populate filtering engine with resolved filter lists
    const promises = [];
    for ( const list of lists ) {
        const promise = list instanceof Promise ? list : Promise.resolve(list);
        promises.push(promise.then(list => consumeList(list)));
    }

    useLists.promise = Promise.all(promises);
    await useLists.promise;
    useLists.promise = null; // eslint-disable-line require-atomic-updates

    // Commit changes
    snfe.freeze();
    snfe.optimize();
}

useLists.promise = null;

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

const fctx = new FilteringContext();
let snfeProxyInstance = null;

class StaticNetFilteringEngine {
    constructor() {
        if ( snfeProxyInstance !== null ) {
            throw new Error('Only a single instance is supported.');
        }
        snfeProxyInstance = this;
    }

    useLists(lists) {
        return useLists(lists);
    }

    matchRequest(details) {
        return snfe.matchRequest(fctx.fromDetails(details));
    }

    matchAndFetchModifiers(details, modifier) {
        return snfe.matchAndFetchModifiers(fctx.fromDetails(details), modifier);
    }

    hasQuery(details) {
        return snfe.hasQuery(details);
    }

    filterQuery(details) {
        const directives = snfe.filterQuery(fctx.fromDetails(details));
        if ( directives === undefined ) { return; }
        return { redirectURL: fctx.redirectURL, directives };
    }

    isBlockImportant() {
        return snfe.isBlockImportant();
    }

    toLogData() {
        return snfe.toLogData();
    }

    createCompiler(parser) {
        return snfe.createCompiler(parser);
    }

    compileList(...args) {
        return compileList(...args);
    }

    serialize() {
        return snfe.serialize();
    }

    deserialize(serialized) {
        return snfe.unserialize(serialized);
    }

    static async create({ noPSL = false } = {}) {
        const instance = new StaticNetFilteringEngine();

        if ( noPSL !== true && !pslInit() ) {
            throw new Error('Failed to initialize public suffix list.');
        }

        return instance;
    }

    static async release() {
        if ( snfeProxyInstance === null ) { return; }
        snfeProxyInstance = null;
        await useLists([]);
    }
}

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

// rollup.js needs module.exports to be set back to the local exports object.
// This is because some of the code (e.g. publicsuffixlist.js) sets
// module.exports. Once all included files are written like ES modules, using
// export statements, this should no longer be necessary.
if ( typeof module !== 'undefined' && typeof exports !== 'undefined' ) {
    module.exports = exports;
}

export {
    enableWASM,
    pslInit,
    StaticNetFilteringEngine,
};