summaryrefslogtreecommitdiff
path: root/extensions/adblock/subscription.vala
blob: 4bc191edac618341aa916416c162cd365037fb09 (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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
 Copyright (C) 2009-2018 Christian Dywan <christian@twotoats.de>
 Copyright (C) 2009-2012 Alexander Butenko <a.butenka@gmail.com>

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

 See the file COPYING for the full license text.
*/

namespace Adblock {
    public enum Directive {
        ALLOW,
        BLOCK
    }

    public static string? fixup_regex (string prefix, string? src) {
        if (src == null) {
            return null;
        }

        var fixed = new StringBuilder ();
        fixed.append (prefix);

        uint i = 0, l = src.length;
        if (src[0] == '*') {
            i++;
        }
        while (i < l) {
            char c = src[i];
            switch (c) {
                case '*':
                    fixed.append (".*"); break;
                case '|':
                case '^':
                case '+':
                    break;
                case '?':
                case '[':
                case ']':
                case '.':
                case '(':
                case ')':
                    fixed.append_printf ("\\%c", c);
                    break;
                default:
                    fixed.append_c (c);
                    break;
            }
            i++;
        }
        return fixed.str;
    }

    public abstract class Feature : Object {
        public virtual Directive? match (string request_uri, string page_uri) throws Error {
            return null;
        }
    }

    public class Subscription : Object {
        public string uri { get; protected construct set; }
        string? _title = null;
        public string? title { get {
            if (_title == null) {
                ensure_headers ();
                if (_title == null) {
                    // Fallback to title from the URI
                    string[] parts = Soup.URI.decode (uri).split ("&");
                    foreach (string part in parts) {
                        if (part.has_prefix ("title=")) {
                            _title = part.substring (6, -1);
                            break;
                        }
                    }
                    if (_title == null) {
                        _title = uri.substring (uri.index_of ("://") + 3, -1);
                    }
                }
            }
            return _title;
        } }
        public bool active { get; set; default = true; }

        HashTable<string, Directive?>? cache = null;
        List<Feature> features;
        Options optslist;
        Whitelist whitelist;
        Keys keys;
        Pattern pattern;
        public File file { get; protected set; }

        public Subscription (string uri, bool active=false) {
            Object (uri: uri, active: active);
        }

        construct {
            // Consider the URI without an optional query
            string base_uri = uri.split ("&")[0];
            if (uri.has_prefix ("file://")) {
                file = File.new_for_uri (base_uri);
            } else {
                string cache_dir = Path.build_filename (Environment.get_user_cache_dir (), Config.PROJECT_NAME, "adblock");
                string filename = Checksum.compute_for_string (ChecksumType.MD5, base_uri, -1);
                file = File.new_for_path (Path.build_filename (cache_dir, filename));
            }
        }

        public void add_feature (Feature feature) {
            features.append (feature);
            size++;
        }

        /* foreach support */
        public new unowned Feature? get (uint index) {
            return features.nth_data (index);
        }
        public uint size { get; private set; }

        void clear () {
            cache = new HashTable<string, Directive?> (str_hash, str_equal);
            optslist = new Options ();
            whitelist = new Whitelist (optslist);
            add_feature (whitelist);
            keys = new Keys (optslist);
            add_feature (keys);
            pattern = new Pattern (optslist);
            add_feature (pattern);
        }

        /*
         * Parse headers only.
         */
        public void ensure_headers () {
            if (!ensure_downloaded (true)) {
                return;
            }

            queue_parse.begin (true);
        }

        /*
         * Attempt to parse filters unless inactive or already cached.
         */
        public bool ensure_parsed () {
            if (!active || cache != null) {
                return active;
            }

            // Skip if this hasn't been downloaded (yet)
            if (!file.query_exists ()) {
                return false;
            }

            queue_parse.begin ();
            return true;
        }

        bool ensure_downloaded (bool headers_only) {
            if (file.query_exists ()) {
                return true;
            }

            try {
                file.get_parent ().make_directory_with_parents ();
            } catch (Error error) {
                // It's no error if the folder already exists
            }

            var download = WebKit.WebContext.get_default ().download_uri (uri.split ("&")[0]);
            download.allow_overwrite = true;
            download.set_destination (file.get_uri ());
            download.finished.connect (() => {
                queue_parse.begin (true);
            });
            return false;
        }

        async void queue_parse (bool headers_only=false) {
            try {
                yield parse (headers_only);
            } catch (Error error) {
                critical ("Failed to parse %s%s: %s", headers_only ? "headers for " : "", uri, error.message);
            }
        }

        /*
         * Parse either headers or filters depending on the flag.
         */
        async void parse (bool headers_only=false) throws Error {
            debug ("Parsing %s, caching %s", uri, file.get_path ());
            clear ();
            var stream = new DataInputStream (file.read ());
            string? line;
            while ((line = stream.read_line (null)) != null) {
                if (line == null) {
                    continue;
                }
                string chomped = line.chomp ();
                if (chomped == "") {
                    continue;
                }
                if (line[0] == '!' && headers_only) {
                    parse_header (chomped);
                } else if (!headers_only) {
                    parse_line (chomped);
                }
            }
        }

        void parse_header (string header) {
            /* Headers come in two forms
               ! Foo: Bar
               ! Some freeform text
             */
            string key = header;
            string value = "";
            if (header.contains (":")) {
                string[] parts = header.split (":", 2);
                if (parts[0] != null && parts[0] != ""
                 && parts[1] != null && parts[1] != "") {
                    key = parts[0].substring (2, -1);
                    value = parts[1].substring (1, -1);
                }
            }
            debug ("Header '%s' says '%s'", key, value);
            if (key == "Title") {
                _title = value;
            }
        }

        void parse_line (string line) throws Error {
            if (line.has_prefix ("@@")) {
                if (line.contains("$") && line.contains ("domain"))
                    return;
                if (line.has_prefix ("@@||")) {
                    add_url_pattern ("^", "whitelist", line.offset (4));
                } else if (line.has_prefix ("@@|")) {
                    add_url_pattern ("^", "whitelist", line.offset (3));
                } else {
                    add_url_pattern ("", "whitelist", line.offset (2));
                }
                return;
            }
            if (line[0] == '[') {
                return;
            }

            // CSS block hiding
            if (line.has_prefix ("##")) {
                // Not implemented here so just skip
                return;
            }
            if (line[0] == '#')
                return;

            if ("#@#" in line)
                return;

            // Per domain CSS hiding rule
            if ("##" in line || "#" in line) {
                // Not implemented here so just skip
                return;
            }

            /* URL blocker rule */
            if (line.has_prefix ("|")) {
                if (line.contains("$"))
                    return;

                if (line.has_prefix ("||")) {
                    add_url_pattern ("", "fulluri", line.offset (2));
                } else {
                    add_url_pattern ("^", "fulluri", line.offset (1));
                }
                return;
            }

            add_url_pattern ("", "uri", line);
            return;
        }

        void add_url_pattern (string prefix, string type, string line) throws Error {
            string[]? data = line.split ("$", 2);
            if (data == null || data[0] == null)
                return;

            string patt, opts;
            patt = data[0];
            opts = type;

            if (data[1] != null)
                opts = type + "," + data[1];

            if (Regex.match_simple ("subdocument", opts,
                RegexCompileFlags.CASELESS, RegexMatchFlags.NOTEMPTY)) {
                return;
            }

            string format_patt = fixup_regex (prefix, patt);
            debug ("got: %s opts %s", format_patt, opts);
            compile_regexp (format_patt, opts);
        }

        void compile_regexp (string? patt, string opts) throws Error {
            if (patt == null) {
                return;
            }

            var regex = new Regex (patt, RegexCompileFlags.OPTIMIZE, RegexMatchFlags.NOTEMPTY);
            // is pattern is already a regular expression?
            if (Regex.match_simple ("^/.*[\\^\\$\\*].*/$", patt,
                RegexCompileFlags.UNGREEDY, RegexMatchFlags.NOTEMPTY)
             || (opts != null && opts.contains ("whitelist"))) {
                debug ("patt: %s", patt);
                if (opts.contains ("whitelist")) {
                    whitelist.insert (patt, regex);
                } else {
                    pattern.insert (patt, regex);
                }
                optslist.insert (patt, opts);
            } else {
                int pos = 0, len;
                int signature_size = 8;
                string sig;
                len = patt.length;

                // Chop up pattern into substrings for faster matching
                for (pos = len - signature_size; pos >= 0; pos--) {
                    sig = patt.offset (pos).ndup (signature_size);
                    // No * nor \\, doesn't look like regex, save chunk as "key"
                    if (!Regex.match_simple ("[\\*]", sig, RegexCompileFlags.UNGREEDY, RegexMatchFlags.NOTEMPTY) && keys.lookup (sig) == null) {
                        keys.insert (sig, regex);
                        optslist.insert (sig, opts);
                    } else {
                        // Starts with * or \\: save as regex
                        if ((sig.has_prefix ("*") || sig.has_prefix("\\")) && pattern.lookup (sig) == null) {
                            pattern.insert (sig, regex);
                            optslist.insert (sig, opts);
                        }
                    }
                }
            }
        }

        public Directive? get_directive (string request_uri, string page_uri) {
            if (!ensure_parsed ()) {
                return null;
            }

            Directive? directive = cache.lookup (request_uri);
            if (directive != null) {
                debug ("%s for %s (%s)", directive.to_string (), request_uri, page_uri);
                return directive;
            }
            return null;
        }
    }
}