aboutsummaryrefslogtreecommitdiffstats
path: root/lib/FrameModule.jsm
blob: 543013ce516d9d3d1f12ac2acb1cdc7dacccdc2a (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
/*******************************************************************************

    ηMatrix - a browser extension to black/white list requests.
    Copyright (C) 2014-2019 The µBlock authors
    Copyright (C) 2019-2020 Alessio Vanni

    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://libregit.spks.xyz/heckyel/ematrix
    uMatrix Home: https://github.com/gorhill/uMatrix
*/

'use strict';

// https://github.com/gorhill/uBlock/issues/800#issuecomment-146580443
var EXPORTED_SYMBOLS = ['contentObserver', 'LocationChangeListener'];

const {interfaces: Ci, utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://gre/modules/XPCOMUtils.jsm');

var hostName = Services.io.newURI(Components.stack.filename, null, null).host;

// Cu.import('resource://gre/modules/Console.jsm');

const getMessageManager = function (win) {
    let iface = win
        .QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIDocShell)
        .sameTypeRootTreeItem
        .QueryInterface(Ci.nsIDocShell)
        .QueryInterface(Ci.nsIInterfaceRequestor);

    try {
        return iface.getInterface(Ci.nsIContentFrameMessageManager);
    } catch (ex) {
        // This can throw. It appears `shouldLoad` can be called *after*  a
        // tab has been closed. For example, a case where this happens all
        // the time (FF38):
        // - Open twitter.com (assuming you have an account and are logged in)
        // - Close twitter.com
        // There will be an exception raised when `shouldLoad` is called
        // to process a XMLHttpRequest with URL `https://twitter.com/i/jot`
        // fired from `https://twitter.com/`, *after*  the tab is closed.
        // In such case, `win` is `about:blank`.
    }
    return null;
};

var contentObserver = {
    classDescription: 'content-policy for ' + hostName,
    classID: Components.ID('{c84283d4-9975-41b7-b1a4-f106af56b51d}'),
    contractID: '@' + hostName + '/content-policy;1',
    ACCEPT: Ci.nsIContentPolicy.ACCEPT,
    MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
    contentBaseURI: 'chrome://' + hostName + '/content/js/',
    cpMessageName: hostName + ':shouldLoad',
    uniqueSandboxId: 1,
    modernFirefox:
    (Services.appinfo.ID === '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'
     || Services.appinfo.ID === '{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}'
     || Services.appinfo.ID === '{9184b6fe-4a5c-484d-8b4b-efbfccbfb514}')
        && Services.vc.compare(Services.appinfo.version, '44') > 0,

    get componentRegistrar() {
        return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
    },

    get categoryManager() {
        return Components.classes['@mozilla.org/categorymanager;1']
            .getService(Ci.nsICategoryManager);
    },

    QueryInterface: XPCOMUtils.generateQI([
        Ci.nsIFactory,
        Ci.nsIObserver,
        Ci.nsIContentPolicy,
        Ci.nsISupportsWeakReference
    ]),

    createInstance: function (outer, iid) {
        if (outer) {
            throw Components.results.NS_ERROR_NO_AGGREGATION;
        }

        return this.QueryInterface(iid);
    },

    register: function () {
        Services.obs.addObserver(this, 'document-element-inserted', true);

        if (!this.modernFirefox) {
            this.componentRegistrar
                .registerFactory(this.classID,
                                 this.classDescription,
                                 this.contractID,
                                 this);
            this.categoryManager
                .addCategoryEntry('content-policy',
                                  this.contractID,
                                  this.contractID,
                                  false,
                                  true);
        }
    },

    unregister: function () {
        Services.obs.removeObserver(this, 'document-element-inserted');

        if (!this.modernFirefox) {
            this.componentRegistrar
                .unregisterFactory(this.classID,
                                   this);
            this.categoryManager
                .deleteCategoryEntry('content-policy',
                                     this.contractID,
                                     false);
        }
    },

    // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy
    // https://bugzil.la/612921
    shouldLoad: function (type, location, origin, context) {
        if (!context) {
            return this.ACCEPT;
        }

        if (!location.schemeIs('http') && !location.schemeIs('https')) {
            return this.ACCEPT;
        }

        let contextWindow;
        if (type === this.MAIN_FRAME) {
            contextWindow = context.contentWindow || context;
        } else if (type === this.SUB_FRAME) {
            contextWindow = context.contentWindow;
        } else {
            contextWindow = (context.ownerDocument || context).defaultView;
        }

        // https://github.com/gorhill/uMatrix/issues/706
        if (!contextWindow) {
            return this.ACCEPT;
        }

        // The context for the toolbar popup is an iframe element here,
        // so check context.top instead of context
        if (!contextWindow.top || !contextWindow.location) {
            return this.ACCEPT;
        }

        let messageManager = getMessageManager(contextWindow);
        if (messageManager === null) {
            return this.ACCEPT;
        }

        let details = {
            rawType: type,
            url: location.asciiSpec
        };

        if (typeof messageManager.sendRpcMessage === 'function') {
            // https://bugzil.la/1092216
            messageManager.sendRpcMessage(this.cpMessageName, details);
        } else {
            // Compatibility for older versions
            messageManager.sendSyncMessage(this.cpMessageName, details);
        }

        return this.ACCEPT;
    },

    initContentScripts: function (win, sandbox) {
        let messager = getMessageManager(win);
        let sandboxId = hostName + ':sb:' + this.uniqueSandboxId++;

        if (sandbox) {
            let sandboxName = [
                win.location.href.slice(0, 100),
                win.document.title.slice(0, 100)
            ].join(' | ');

            // https://github.com/gorhill/uMatrix/issues/325
            // "Pass sameZoneAs to sandbox constructor to make GCs cheaper"
            sandbox = Cu.Sandbox([win], {
                sameZoneAs: win.top,
                sandboxName: sandboxId + '[' + sandboxName + ']',
                sandboxPrototype: win,
                wantComponents: false,
                wantXHRConstructor: false
            });

            sandbox.injectScript = function (script) {
                Services.scriptloader.loadSubScript(script, sandbox);
            };
        }
        else {
            sandbox = win;
        }

        sandbox._sandboxId_ = sandboxId;
        sandbox.sendAsyncMessage = messager.sendAsyncMessage;

        sandbox.addMessageListener = function (callback) {
            if (sandbox._messageListener_) {
                sandbox.removeMessageListener();
            }

            sandbox._messageListener_ = function (message) {
                callback(message.data);
            };

            messager.addMessageListener(sandbox._sandboxId_,
                                        sandbox._messageListener_);
            messager.addMessageListener(hostName + ':broadcast',
                                        sandbox._messageListener_);
        };

        sandbox.removeMessageListener = function () {
            try {
                messager.removeMessageListener(sandbox._sandboxId_,
                                               sandbox._messageListener_);
                messager.removeMessageListener(hostName + ':broadcast',
                                               sandbox._messageListener_);
            } catch (ex) {
                // It throws sometimes, mostly when the popup closes
            }

            sandbox._messageListener_ = null;
        };

        return sandbox;
    },

    observe: function (doc) {
        let win = doc.defaultView;
        if (!win) {
            return;
        }

        let loc = win.location;
        if (!loc) {
            return;
        }

        // https://github.com/gorhill/uBlock/issues/260
        // TODO: We may have to skip more types, for now let's be
        // conservative, i.e. let's not test against `text/html`.
        if (doc.contentType.lastIndexOf('image/', 0) === 0) {
            return;
        }

        if (loc.protocol !== 'http:'
            && loc.protocol !== 'https:'
            && loc.protocol !== 'file:') {
            if (loc.protocol === 'chrome:' && loc.host === hostName) {
                this.initContentScripts(win);
            }

            // What about data: and about:blank?
            return;
        }

        let lss = Services.scriptloader.loadSubScript;
        let sandbox = this.initContentScripts(win, true);

        // Can throw with attempts at injecting into non-HTML document.
        // Example: https://a.pomf.se/avonjf.webm
        try {
            lss(this.contentBaseURI + 'vapi-client.js', sandbox);
            lss(this.contentBaseURI + 'contentscript-start.js', sandbox);
        } catch (ex) {
            return; // don't further try to inject anything
        }

        let docReady = (e) => {
            let doc = e.target;
            doc.removeEventListener(e.type, docReady, true);
            lss(this.contentBaseURI + 'contentscript.js', sandbox);
        };

        if (doc.readyState === 'loading') {
            doc.addEventListener('DOMContentLoaded', docReady, true);
        } else {
            docReady({
                target: doc,
                type: 'DOMContentLoaded',
            });
        }
    }
};

var locationChangedMessageName = hostName + ':locationChanged';

var LocationChangeListener = function (docShell) {
    if (!docShell) {
        return;
    }

    var requestor = docShell.QueryInterface(Ci.nsIInterfaceRequestor);
    var ds = requestor.getInterface(Ci.nsIWebProgress);
    var mm = requestor.getInterface(Ci.nsIContentFrameMessageManager);

    if (ds && mm && typeof mm.sendAsyncMessage === 'function') {
        this.docShell = ds;
        this.messageManager = mm;
        ds.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION);
    }
};

LocationChangeListener.prototype.QueryInterface = XPCOMUtils.generateQI([
    'nsIWebProgressListener',
    'nsISupportsWeakReference'
]);

LocationChangeListener.prototype.onLocationChange =
    function (webProgress, request, location, flags) {
        if (!webProgress.isTopLevel) {
            return;
        }
        this.messageManager.sendAsyncMessage(locationChangedMessageName, {
            url: location.asciiSpec,
            flags: flags,
        });
    };

contentObserver.register();