/******************************************************************************* ηMatrix - a browser extension to black/white list requests. Copyright (C) 2014-2019 The uMatrix/uBlock Origin authors Copyright (C) 2019 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://gitlab.com/vannilla/ematrix uMatrix Home: https://github.com/gorhill/uMatrix */ /* jshint bitwise: false, esnext: true */ /* global self, Components, punycode */ // For background page 'use strict'; /******************************************************************************/ (function () { const {classes: Cc, interfaces: Ci, utils: Cu} = Components; const {Services} = Cu.import('resource://gre/modules/Services.jsm', null); let vAPI = self.vAPI; // Guaranteed to be initialized by vapi-core.js vAPI.browserSettings = { // For now, only booleans. originalValues: {}, rememberOriginalValue: function (path, setting) { let key = path + '.' + setting; if (this.originalValues.hasOwnProperty(key)) { return; } let hasUserValue; let branch = Services.prefs.getBranch(path + '.'); try { hasUserValue = branch.prefHasUserValue(setting); } catch (ex) { // Ignore } if (hasUserValue !== undefined) { this.originalValues[key] = hasUserValue ? this.getValue(path, setting) : undefined; } }, clear: function (path, setting) { let key = path + '.' + setting; // Value was not overriden -- nothing to restore if (this.originalValues.hasOwnProperty(key) === false) { return; } let value = this.originalValues[key]; // https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979 // Forget the value immediately, it may change outside of // uBlock control. delete this.originalValues[key]; // Original value was a default one if (value === undefined) { try { Services.prefs.getBranch(path + '.').clearUserPref(setting); } catch (ex) { // Ignore } return; } // Reset to original value this.setValue(path, setting, value); }, getValue: function (path, setting) { let branch = Services.prefs.getBranch(path + '.'); try { switch (branch.getPrefType(setting)) { case branch.PREF_INT: return branch.getIntPref(setting); case branch.PREF_BOOL: return branch.getBoolPref(setting); default: // not supported return; } } catch (e) { // Ignore } }, setValue: function (path, setting, value) { let branch = Services.prefs.getBranch(path + '.'); try { switch (typeof value) { case 'number': return branch.setIntPref(setting, value); case 'boolean': return branch.setBoolPref(setting, value); default: // not supported return; } } catch (e) { // Ignore } }, setSetting: function (setting, value) { switch (setting) { case 'prefetching': this.rememberOriginalValue('network', 'prefetch-next'); // https://bugzilla.mozilla.org/show_bug.cgi?id=814169 // Sigh. // eMatrix: doesn't seem the case for Pale // Moon/Basilisk, but let's keep this anyway this.rememberOriginalValue('network.http', 'speculative-parallel-limit'); // https://github.com/gorhill/uBlock/issues/292 // "true" means "do not disable", i.e. leave entry alone if (value) { this.clear('network', 'prefetch-next'); this.clear('network.http', 'speculative-parallel-limit'); } else { this.setValue('network', 'prefetch-next', false); this.setValue('network.http', 'speculative-parallel-limit', 0); } break; case 'hyperlinkAuditing': this.rememberOriginalValue('browser', 'send_pings'); this.rememberOriginalValue('beacon', 'enabled'); // https://github.com/gorhill/uBlock/issues/292 // "true" means "do not disable", i.e. leave entry alone if (value) { this.clear('browser', 'send_pings'); this.clear('beacon', 'enabled'); } else { this.setValue('browser', 'send_pings', false); this.setValue('beacon', 'enabled', false); } break; case 'webrtcIPAddress': let prefName; let prefVal; // https://github.com/gorhill/uBlock/issues/894 // Do not disable completely WebRTC if it can be avoided. FF42+ // has a `media.peerconnection.ice.default_address_only` pref which // purpose is to prevent local IP address leakage. if (this.getValue('media.peerconnection', 'ice.default_address_only') !== undefined) { prefName = 'ice.default_address_only'; prefVal = true; } else { prefName = 'enabled'; prefVal = false; } this.rememberOriginalValue('media.peerconnection', prefName); if (value) { this.clear('media.peerconnection', prefName); } else { this.setValue('media.peerconnection', prefName, prefVal); } break; default: break; } }, set: function (details) { for (let setting in details) { if (details.hasOwnProperty(setting) === false) { continue; } this.setSetting(setting, !!details[setting]); } }, restoreAll: function () { let pos; for (let key in this.originalValues) { if (this.originalValues.hasOwnProperty(key) === false) { continue; } pos = key.lastIndexOf('.'); this.clear(key.slice(0, pos), key.slice(pos + 1)); } }, }; vAPI.addCleanUpTask(vAPI.browserSettings .restoreAll.bind(vAPI.browserSettings)); // API matches that of chrome.storage.local: // https://developer.chrome.com/extensions/storage vAPI.storage = (function () { let db = null; let vacuumTimer = null; let close = function () { if (vacuumTimer !== null) { clearTimeout(vacuumTimer); vacuumTimer = null; } if (db === null) { return; } db.asyncClose(); db = null; }; let open = function () { if (db !== null) { return db; } // Create path let path = Services.dirsvc.get('ProfD', Ci.nsIFile); path.append('ematrix-data'); if (!path.exists()) { path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8)); } if (!path.isDirectory()) { throw Error('Should be a directory...'); } let path2 = Services.dirsvc.get('ProfD', Ci.nsIFile); path2.append('extension-data'); path2.append(location.host + '.sqlite'); if (path2.exists()) { path2.moveTo(path, location.host+'.sqlite'); } path.append(location.host + '.sqlite'); // Open database try { db = Services.storage.openDatabase(path); if (db.connectionReady === false) { db.asyncClose(); db = null; } } catch (ex) { // Ignore } if (db === null) { return null; } // Database was opened, register cleanup task vAPI.addCleanUpTask(close); // Setup database db.createAsyncStatement('CREATE TABLE IF NOT EXISTS ' +'"settings" ("name" ' +'TEXT PRIMARY KEY NOT NULL, ' +'"value" TEXT);') .executeAsync(); if (vacuum !== null) { vacuumTimer = vAPI.setTimeout(vacuum, 60000); } return db; }; // Vacuum only once, and only while idle let vacuum = function () { vacuumTimer = null; if (db === null) { return; } let idleSvc = Cc['@mozilla.org/widget/idleservice;1'] .getService(Ci.nsIIdleService); if (idleSvc.idleTime < 60000) { vacuumTimer = vAPI.setTimeout(vacuum, 60000); return; } db.createAsyncStatement('VACUUM').executeAsync(); vacuum = null; }; // Execute a query let runStatement = function (stmt, callback) { let result = {}; stmt.executeAsync({ handleResult: function (rows) { if (!rows || typeof callback !== 'function') { return; } let row; while ((row = rows.getNextRow())) { // we assume that there will be two columns, since we're // using it only for preferences // eMatrix: the above comment is obsolete // (it's not used just for preferences // anymore), but we still expect two columns. let res = row.getResultByIndex(0); result[res] = row.getResultByIndex(1); } }, handleCompletion: function (reason) { if (typeof callback === 'function' && reason === 0) { callback(result); } }, handleError: function (error) { console.error('SQLite error ', error.result, error.message); // Caller expects an answer regardless of failure. if (typeof callback === 'function' ) { callback(null); } }, }); }; let bindNames = function (stmt, names) { if (Array.isArray(names) === false || names.length === 0) { return; } let params = stmt.newBindingParamsArray(); for (let i=names.length-1; i>=0; --i) { let bp = params.newBindingParams(); bp.bindByName('name', names[i]); params.addParams(bp); } stmt.bindParameters(params); }; let clear = function (callback) { if (open() === null) { if (typeof callback === 'function') { callback(); } return; } runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback); }; let getBytesInUse = function (keys, callback) { if (typeof callback !== 'function') { return; } if (open() === null) { callback(0); return; } let stmt; if (Array.isArray(keys)) { stmt = db.createAsyncStatement('SELECT "size" AS "size", ' +'SUM(LENGTH("value")) ' +'FROM "settings" WHERE ' +'"name" = :name'); bindNames(keys); } else { stmt = db.createAsyncStatement('SELECT "size" AS "size", ' +'SUM(LENGTH("value")) ' +'FROM "settings"'); } runStatement(stmt, function (result) { callback(result.size); }); }; let read = function (details, callback) { if (typeof callback !== 'function') { return; } let prepareResult = function (result) { for (let key in result) { if (result.hasOwnProperty(key) === false) { continue; } result[key] = JSON.parse(result[key]); } if (typeof details === 'object' && details !== null) { for (let key in details) { if (result.hasOwnProperty(key) === false) { result[key] = details[key]; } } } callback(result); }; if (open() === null) { prepareResult({}); return; } let names = []; if (details !== null) { if (Array.isArray(details)) { names = details; } else if (typeof details === 'object') { names = Object.keys(details); } else { names = [details.toString()]; } } let stmt; if (names.length === 0) { stmt = db.createAsyncStatement('SELECT * FROM "settings"'); } else { stmt = db.createAsyncStatement('SELECT * FROM "settings" ' +'WHERE "name" = :name'); bindNames(stmt, names); } runStatement(stmt, prepareResult); }; let remove = function (keys, callback) { if (open() === null) { if (typeof callback === 'function') { callback(); } return; } var stmt = db.createAsyncStatement('DELETE FROM "settings" ' +'WHERE "name" = :name'); bindNames(stmt, typeof keys === 'string' ? [keys] : keys); runStatement(stmt, callback); }; let write = function (details, callback) { if (open() === null) { if (typeof callback === 'function') { callback(); } return; } let stmt = db.createAsyncStatement('INSERT OR REPLACE INTO ' +'"settings" ("name", "value") ' +'VALUES(:name, :value)'); let params = stmt.newBindingParamsArray(); for (let key in details) { if (details.hasOwnProperty(key) === false) { continue; } let bp = params.newBindingParams(); bp.bindByName('name', key); bp.bindByName('value', JSON.stringify(details[key])); params.addParams(bp); } if (params.length === 0) { return; } stmt.bindParameters(params); runStatement(stmt, callback); }; // Export API var api = { QUOTA_BYTES: 100 * 1024 * 1024, clear: clear, get: read, getBytesInUse: getBytesInUse, remove: remove, set: write }; return api; })(); vAPI.cacheStorage = vAPI.storage; // browser-handling utilities vAPI.browser = {}; vAPI.browser.getTabBrowser = function (win) { return win && win.gBrowser || null; }; vAPI.browser.getOwnerWindow = function (target) { if (target.ownerDocument) { return target.ownerDocument.defaultView; } return null; }; // Icon-related stuff vAPI.setIcon = function (tabId, iconId, badge) { // If badge is undefined, then setIcon was called from the // TabSelect event let win; if (badge === undefined) { win = iconId; } else { win = vAPI.window.getCurrentWindow(); } let tabBrowser = vAPI.browser.getTabBrowser(win); if (tabBrowser === null) { return; } let curTabId = vAPI.tabs.manager.tabIdFromTarget(tabBrowser.selectedTab); let tb = vAPI.toolbarButton; // from 'TabSelect' event if (tabId === undefined) { tabId = curTabId; } else if (badge !== undefined) { tb.tabs[tabId] = { badge: badge, img: iconId }; } if (tabId === curTabId) { tb.updateState(win, tabId); } }; // Internal message passing mechanism vAPI.messaging = { get globalMessageManager() { return Cc['@mozilla.org/globalmessagemanager;1'] .getService(Ci.nsIMessageListenerManager); }, frameScript: vAPI.getURL('frameScript.js'), listeners: {}, defaultHandler: null, NOOPFUNC: function(){}, UNHANDLED: 'vAPI.messaging.notHandled' }; vAPI.messaging.listen = function (listenerName, callback) { this.listeners[listenerName] = callback; }; vAPI.messaging.onMessage = function ({target, data}) { let messageManager = target.messageManager; if (!messageManager) { // Message came from a popup, and its message manager is // not usable. So instead we broadcast to the parent // window. messageManager = vAPI.browser. getOwnerWindow(target.webNavigation .QueryInterface(Ci.nsIDocShell) .chromeEventHandler).messageManager; } let channelNameRaw = data.channelName; let pos = channelNameRaw.indexOf('|'); let channelName = channelNameRaw.slice(pos + 1); let callback = vAPI.messaging.NOOPFUNC; if (data.requestId !== undefined) { callback = CallbackWrapper.factory(messageManager, channelName, channelNameRaw.slice(0, pos), data.requestId).callback; } let sender = { tab: { id: vAPI.tabs.manager.tabIdFromTarget(target) } }; // Specific handler let r = vAPI.messaging.UNHANDLED; let listener = vAPI.messaging.listeners[channelName]; if (typeof listener === 'function') { r = listener(data.msg, sender, callback); } if (r !== vAPI.messaging.UNHANDLED) { return; } // Default handler r = vAPI.messaging.defaultHandler(data.msg, sender, callback); if (r !== vAPI.messaging.UNHANDLED) { return; } console.error('eMatrix> messaging > unknown request: %o', data); // Unhandled: Need to callback anyways in case caller expected // an answer, or else there is a memory leak on caller's side callback(); }; vAPI.messaging.setup = function (defaultHandler) { // Already setup? if (this.defaultHandler !== null) { return; } if (typeof defaultHandler !== 'function') { defaultHandler = function () { return vAPI.messaging.UNHANDLED; }; } this.defaultHandler = defaultHandler; this.globalMessageManager.addMessageListener(location.host + ':background', this.onMessage); this.globalMessageManager.loadFrameScript(this.frameScript, true); vAPI.addCleanUpTask(function () { let gmm = vAPI.messaging.globalMessageManager; gmm.removeDelayedFrameScript(vAPI.messaging.frameScript); gmm.removeMessageListener(location.host + ':background', vAPI.messaging.onMessage); }); }; vAPI.messaging.broadcast = function (message) { this.globalMessageManager .broadcastAsyncMessage(location.host + ':broadcast', JSON.stringify({ broadcast: true, msg: message})); }; let CallbackWrapper = function (messageManager, channelName, listenerId, requestId) { // This allows to avoid creating a closure for every single // message which expects an answer. Having a closure created // each time a message is processed has been always bothering // me. Another benefit of the implementation here is to reuse // the callback proxy object, so less memory churning. // // https://developers.google.com/speed/articles/optimizing-javascript // "Creating a closure is significantly slower then creating // an inner function without a closure, and much slower than // reusing a static function" // // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html // "the dreaded 'uniformly slow code' case where every // function takes 1% of CPU and you have to make one hundred // separate performance optimizations to improve performance // at all" // // http://jsperf.com/closure-no-closure/2 this.callback = this.proxy.bind(this); // bind once this.init(messageManager, channelName, listenerId, requestId); }; CallbackWrapper.junkyard = []; CallbackWrapper.factory = function (messageManager, channelName, listenerId, requestId) { let wrapper = CallbackWrapper.junkyard.pop(); if (wrapper) { wrapper.init(messageManager, channelName, listenerId, requestId); return wrapper; } return new CallbackWrapper(messageManager, channelName, listenerId, requestId); }; CallbackWrapper.prototype.init = function (messageManager, channelName, listenerId, requestId) { this.messageManager = messageManager; this.channelName = channelName; this.listenerId = listenerId; this.requestId = requestId; }; CallbackWrapper.prototype.proxy = function (response) { let message = JSON.stringify({ requestId: this.requestId, channelName: this.channelName, msg: response !== undefined ? response : null }); if (this.messageManager.sendAsyncMessage) { this.messageManager.sendAsyncMessage(this.listenerId, message); } else { this.messageManager.broadcastAsyncMessage(this.listenerId, message); } // Mark for reuse this.messageManager = this.channelName = this.requestId = this.listenerId = null; CallbackWrapper.junkyard.push(this); }; let httpRequestHeadersFactory = function (channel) { let entry = httpRequestHeadersFactory.junkyard.pop(); if (entry) { return entry.init(channel); } return new HTTPRequestHeaders(channel); }; httpRequestHeadersFactory.junkyard = []; let HTTPRequestHeaders = function (channel) { this.init(channel); }; HTTPRequestHeaders.prototype.init = function (channel) { this.channel = channel; this.headers = new Array(); this.originalHeaderNames = new Array(); channel.visitRequestHeaders({ visitHeader: function (name, value) { this.headers.push({name: name, value: value}); this.originalHeaderNames.push(name); }.bind(this) }); return this; }; HTTPRequestHeaders.prototype.dispose = function () { this.channel = null; this.headers = null; this.originalHeaderNames = null; httpRequestHeadersFactory.junkyard.push(this); }; HTTPRequestHeaders.prototype.update = function () { let newHeaderNames = new Set(); for (let header of this.headers) { this.setHeader(header.name, header.value, true); newHeaderNames.add(header.name); } //Clear any headers that were removed for (let name of this.originalHeaderNames) { if (!newHeaderNames.has(name)) { this.channel.setRequestHeader(name, '', false); } } }; HTTPRequestHeaders.prototype.getHeader = function (name) { try { return this.channel.getRequestHeader(name); } catch (e) { // Ignore } return ''; }; HTTPRequestHeaders.prototype.setHeader = function (name, newValue, create) { let oldValue = this.getHeader(name); if (newValue === oldValue) { return false; } if (oldValue === '' && create !== true) { return false; } this.channel.setRequestHeader(name, newValue, false); return true; }; let httpObserver = { classDescription: 'net-channel-event-sinks for ' + location.host, classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'), contractID: '@' + location.host + '/net-channel-event-sinks;1', REQDATAKEY: location.host + 'reqdata', ABORT: Components.results.NS_BINDING_ABORTED, ACCEPT: Components.results.NS_SUCCEEDED, // Request types: // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants // eMatrix: we can just use nsIContentPolicy's built-in // constants, can we? frameTypeMap: { 6: 'main_frame', 7: 'sub_frame' }, typeMap: { 1: 'other', 2: 'script', 3: 'image', 4: 'stylesheet', 5: 'object', 6: 'main_frame', 7: 'sub_frame', 9: 'xbl', 10: 'ping', 11: 'xmlhttprequest', 12: 'object', 13: 'xml_dtd', 14: 'font', 15: 'media', 16: 'websocket', 17: 'csp_report', 18: 'xslt', 19: 'beacon', 20: 'xmlhttprequest', 21: 'imageset', 22: 'web_manifest' }, mimeTypeMap: { 'audio': 15, 'video': 15 }, get componentRegistrar () { return Components.manager.QueryInterface(Ci.nsIComponentRegistrar); }, get categoryManager () { return Cc['@mozilla.org/categorymanager;1'] .getService(Ci.nsICategoryManager); }, QueryInterface: (function () { var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null); return XPCOMUtils.generateQI([ Ci.nsIFactory, Ci.nsIObserver, Ci.nsIChannelEventSink, Ci.nsISupportsWeakReference ]); })(), createInstance: function (outer, iid) { if (outer) { throw Components.results.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(iid); }, register: function () { this.pendingRingBufferInit(); Services.obs.addObserver(this, 'http-on-modify-request', true); Services.obs.addObserver(this, 'http-on-examine-response', true); Services.obs.addObserver(this, 'http-on-examine-cached-response', true); // Guard against stale instances not having been unregistered if (this.componentRegistrar.isCIDRegistered(this.classID)) { try { this.componentRegistrar .unregisterFactory(this.classID, Components.manager .getClassObject(this.classID, Ci.nsIFactory)); } catch (ex) { console.error('eMatrix> httpObserver > ' +'unable to unregister stale instance: ', ex); } } this.componentRegistrar.registerFactory(this.classID, this.classDescription, this.contractID, this); this.categoryManager.addCategoryEntry('net-channel-event-sinks', this.contractID, this.contractID, false, true); }, unregister: function () { Services.obs.removeObserver(this, 'http-on-modify-request'); Services.obs.removeObserver(this, 'http-on-examine-response'); Services.obs.removeObserver(this, 'http-on-examine-cached-response'); this.componentRegistrar.unregisterFactory(this.classID, this); this.categoryManager.deleteCategoryEntry('net-channel-event-sinks', this.contractID, false); }, PendingRequest: function () { this.rawType = 0; this.tabId = 0; this._key = ''; // key is url, from URI.spec }, // If all work fine, this map should not grow indefinitely. It // can have stale items in it, but these will be taken care of // when entries in the ring buffer are overwritten. pendingURLToIndex: new Map(), pendingWritePointer: 0, pendingRingBuffer: new Array(256), pendingRingBufferInit: function () { // Use and reuse pre-allocated PendingRequest objects = // less memory churning. for (let i=this.pendingRingBuffer.length-1; i>=0; --i) { this.pendingRingBuffer[i] = new this.PendingRequest(); } }, createPendingRequest: function (url) { // Pending request ring buffer: // +-------+-------+-------+-------+-------+-------+------- // |0 |1 |2 |3 |4 |5 |... // +-------+-------+-------+-------+-------+-------+------- // // URL to ring buffer index map: // { k = URL, s = ring buffer indices } // // s is a string which character codes map to ring buffer // indices -- for when the same URL is received multiple times // by shouldLoadListener() before the existing one is serviced // by the network request observer. I believe the use of a // string in lieu of an array reduces memory churning. let bucket; let i = this.pendingWritePointer; this.pendingWritePointer = i + 1 & 255; let preq = this.pendingRingBuffer[i]; let si = String.fromCharCode(i); // Cleanup unserviced pending request if (preq._key !== '') { bucket = this.pendingURLToIndex.get(preq._key); if (bucket.length === 1) { this.pendingURLToIndex.delete(preq._key); } else { let pos = bucket.indexOf(si); this.pendingURLToIndex.set(preq._key, bucket.slice(0, pos) + bucket.slice(pos + 1)); } } bucket = this.pendingURLToIndex.get(url); this.pendingURLToIndex.set(url, bucket === undefined ? si : bucket + si); preq._key = url; return preq; }, lookupPendingRequest: function (url) { let bucket = this.pendingURLToIndex.get(url); if (bucket === undefined) { return null; } let i = bucket.charCodeAt(0); if (bucket.length === 1) { this.pendingURLToIndex.delete(url); } else { this.pendingURLToIndex.set(url, bucket.slice(1)); } let preq = this.pendingRingBuffer[i]; preq._key = ''; // mark as "serviced" return preq; }, handleRequest: function (channel, URI, tabId, rawType) { let type = this.typeMap[rawType] || 'other'; let onBeforeRequest = vAPI.net.onBeforeRequest; if (onBeforeRequest.types === null || onBeforeRequest.types.has(type)) { let result = onBeforeRequest.callback({ parentFrameId: type === 'main_frame' ? -1 : 0, tabId: tabId, type: type, url: URI.asciiSpec }); if (typeof result === 'object') { channel.cancel(this.ABORT); return true; } } let onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders; if (onBeforeSendHeaders.types === null || onBeforeSendHeaders.types.has(type)) { let requestHeaders = httpRequestHeadersFactory(channel); let newHeaders = onBeforeSendHeaders.callback({ parentFrameId: type === 'main_frame' ? -1 : 0, requestHeaders: requestHeaders.headers, tabId: tabId, type: type, url: URI.asciiSpec, method: channel.requestMethod }); if (newHeaders) { requestHeaders.update(); } requestHeaders.dispose(); } return false; }, channelDataFromChannel: function (channel) { if (channel instanceof Ci.nsIWritablePropertyBag) { try { return channel.getProperty(this.REQDATAKEY) || null; } catch (ex) { // Ignore } } return null; }, // https://github.com/gorhill/uMatrix/issues/165 // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request // Not sure `ematrix:shouldLoad` is still needed, eMatrix does // not care about embedded frames topography. // Also: // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts tabIdFromChannel: function (channel) { let lc; try { lc = channel.notificationCallbacks.getInterface(Ci.nsILoadContext); } catch(ex) { // Ignore } if (!lc) { try { lc = channel.loadGroup.notificationCallbacks .getInterface(Ci.nsILoadContext); } catch(ex) { // Ignore } if (!lc) { return vAPI.noTabId; } } if (lc.topFrameElement) { return vAPI.tabs.manager.tabIdFromTarget(lc.topFrameElement); } let win; try { win = lc.associatedWindow; } catch (ex) { // Ignore } if (!win) { return vAPI.noTabId; } if (win.top) { win = win.top; } let tabBrowser; try { tabBrowser = vAPI.browser.getTabBrowser (win.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsIDocShell).rootTreeItem .QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindow)); } catch (ex) { // Ignore } if (!tabBrowser) { return vAPI.noTabId; } if (tabBrowser.getBrowserForContentWindow) { return vAPI.tabs.manager .tabIdFromTarget(tabBrowser.getBrowserForContentWindow(win)); } // Falling back onto _getTabForContentWindow to ensure older // versions of Firefox work well. return tabBrowser._getTabForContentWindow ? vAPI.tabs.manager .tabIdFromTarget(tabBrowser._getTabForContentWindow(win)) : vAPI.noTabId; }, rawtypeFromContentType: function (channel) { let mime = channel.contentType; if (!mime) { return 0; } let pos = mime.indexOf('/'); if (pos === -1) { pos = mime.length; } return this.mimeTypeMap[mime.slice(0, pos)] || 0; }, observe: function (channel, topic) { if (channel instanceof Ci.nsIHttpChannel === false) { return; } let URI = channel.URI; let channelData = this.channelDataFromChannel(channel); if (topic.lastIndexOf('http-on-examine-', 0) === 0) { if (channelData === null) { return; } let type = this.frameTypeMap[channelData[1]]; if (!type) { return; } // topic = ['Content-Security-Policy', // 'Content-Security-Policy-Report-Only']; // // Can send empty responseHeaders as these headers are // only added to and then merged. // // TODO: Find better place for this, needs to be set // before onHeadersReceived.callback. Web workers not // blocked in Pale Moon as child-src currently // unavailable, see: // // https://github.com/MoonchildProductions/Pale-Moon/issues/949 // // eMatrix: as of Pale Moon 28 it seems child-src is // available and depracated(?) if (ηMatrix.cspNoWorker === undefined) { // ηMatrix.cspNoWorker = "child-src 'none'; " // +"frame-src data: blob: *; " // +"report-uri about:blank"; ηMatrix.cspNoWorker = "worker-src 'none'; " +"frame-src data: blob: *; " +"report-uri about:blank"; } let result = vAPI.net.onHeadersReceived.callback({ parentFrameId: type === 'main_frame' ? -1 : 0, responseHeaders: [], tabId: channelData[0], type: type, url: URI.asciiSpec }); if (result) { for (let header of result.responseHeaders) { channel.setResponseHeader(header.name, header.value, true); } } return; } // http-on-modify-request // The channel was previously serviced. if (channelData !== null) { this.handleRequest(channel, URI, channelData[0], channelData[1]); return; } // The channel was never serviced. let tabId; let pendingRequest = this.lookupPendingRequest(URI.asciiSpec); let rawType = 1; let loadInfo = channel.loadInfo; // https://github.com/gorhill/uMatrix/issues/390#issuecomment-155717004 if (loadInfo) { rawType = (loadInfo.externalContentPolicyType !== undefined) ? loadInfo.externalContentPolicyType : loadInfo.contentPolicyType; if (!rawType) { rawType = 1; } } if (pendingRequest !== null) { tabId = pendingRequest.tabId; // https://github.com/gorhill/uBlock/issues/654 // Use the request type from the HTTP observer point of view. if (rawType !== 1) { pendingRequest.rawType = rawType; } else { rawType = pendingRequest.rawType; } } else { tabId = this.tabIdFromChannel(channel); } if (this.handleRequest(channel, URI, tabId, rawType)) { return; } if (channel instanceof Ci.nsIWritablePropertyBag === false) { return; } // Carry data for behind-the-scene redirects channel.setProperty(this.REQDATAKEY, [tabId, rawType]); }, asyncOnChannelRedirect: function (oldChannel, newChannel, flags, callback) { // contentPolicy.shouldLoad doesn't detect redirects, this // needs to be used // If error thrown, the redirect will fail try { let URI = newChannel.URI; if (!URI.schemeIs('http') && !URI.schemeIs('https')) { return; } if (newChannel instanceof Ci.nsIWritablePropertyBag === false) { return; } let channelData = this.channelDataFromChannel(oldChannel); if (channelData === null) { return; } // Carry the data on in case of multiple redirects newChannel.setProperty(this.REQDATAKEY, channelData); } catch (ex) { // console.error(ex); // Ignore } finally { callback.onRedirectVerifyCallback(this.ACCEPT); } } }; vAPI.net = {}; vAPI.net.registerListeners = function () { this.onBeforeRequest.types = this.onBeforeRequest.types ? new Set(this.onBeforeRequest.types) : null; this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ? new Set(this.onBeforeSendHeaders.types) : null; let shouldLoadListenerMessageName = location.host + ':shouldLoad'; let shouldLoadListener = function (e) { let details = e.data; let pendingReq = httpObserver.createPendingRequest(details.url); pendingReq.rawType = details.rawType; pendingReq.tabId = vAPI.tabs.manager.tabIdFromTarget(e.target); }; // https://github.com/gorhill/uMatrix/issues/200 // We need this only for Firefox 34 and less: the tab id is derived from // the origin of the message. if (!vAPI.modernFirefox) { vAPI.messaging.globalMessageManager .addMessageListener(shouldLoadListenerMessageName, shouldLoadListener); } httpObserver.register(); vAPI.addCleanUpTask(function () { if (!vAPI.modernFirefox) { vAPI.messaging.globalMessageManager .removeMessageListener(shouldLoadListenerMessageName, shouldLoadListener); } httpObserver.unregister(); }); }; vAPI.toolbarButton = { id: location.host + '-button', type: 'view', viewId: location.host + '-panel', label: vAPI.app.name, tooltiptext: vAPI.app.name, tabs: {/*tabId: {badge: 0, img: boolean}*/}, init: null, codePath: '' }; // Non-Fennec: common code paths. (function () { if (vAPI.fennec) { return; } let tbb = vAPI.toolbarButton; let popupCommittedWidth = 0; let popupCommittedHeight = 0; tbb.onViewShowing = function ({target}) { popupCommittedWidth = popupCommittedHeight = 0; target.firstChild.setAttribute('src', vAPI.getURL('popup.html')); }; tbb.onViewHiding = function ({target}) { target.parentNode.style.maxWidth = ''; target.firstChild.setAttribute('src', 'about:blank'); }; tbb.updateState = function (win, tabId) { let button = win.document.getElementById(this.id); if (!button) { return; } let icon = this.tabs[tabId]; button.setAttribute('badge', icon && icon.badge || ''); button.classList.toggle('off', !icon || !icon.img); let iconId = icon && icon.img ? icon.img : 'off'; icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')'; button.style.listStyleImage = icon; }; tbb.populatePanel = function (doc, panel) { panel.setAttribute('id', this.viewId); let iframe = doc.createElement('iframe'); iframe.setAttribute('type', 'content'); panel.appendChild(iframe); let toPx = function (pixels) { return pixels.toString() + 'px'; }; let scrollBarWidth = 0; let resizeTimer = null; let resizePopupDelayed = function (attempts) { if (resizeTimer !== null) { return false; } // Sanity check attempts = (attempts || 0) + 1; if ( attempts > 1/*000*/ ) { //console.error('eMatrix> resizePopupDelayed: giving up after too many attempts'); return false; } resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts); return true; }; let resizePopup = function (attempts) { resizeTimer = null; panel.parentNode.style.maxWidth = 'none'; let body = iframe.contentDocument.body; // https://github.com/gorhill/uMatrix/issues/301 // Don't resize if committed size did not change. if (popupCommittedWidth === body.clientWidth && popupCommittedHeight === body.clientHeight) { return; } // We set a limit for height let height = Math.min(body.clientHeight, 600); // https://github.com/chrisaljoudi/uBlock/issues/730 // Voodoo programming: this recipe works panel.style.setProperty('height', toPx(height)); iframe.style.setProperty('height', toPx(height)); // Adjust width for presence/absence of vertical scroll bar which may // have appeared as a result of last operation. let contentWindow = iframe.contentWindow; let width = body.clientWidth; if (contentWindow.scrollMaxY !== 0) { width += scrollBarWidth; } panel.style.setProperty('width', toPx(width)); // scrollMaxX should always be zero once we know the scrollbar width if (contentWindow.scrollMaxX !== 0) { scrollBarWidth = contentWindow.scrollMaxX; width += scrollBarWidth; panel.style.setProperty('width', toPx(width)); } if (iframe.clientHeight !== height || panel.clientWidth !== width) { if (resizePopupDelayed(attempts)) { return; } // resizePopupDelayed won't be called again, so commit // dimentsions. } popupCommittedWidth = body.clientWidth; popupCommittedHeight = body.clientHeight; }; let onResizeRequested = function () { let body = iframe.contentDocument.body; if (body.getAttribute('data-resize-popup') !== 'true') { return; } body.removeAttribute('data-resize-popup'); resizePopupDelayed(); }; let onPopupReady = function () { let win = this.contentWindow; if (!win || win.location.host !== location.host) { return; } if (typeof tbb.onBeforePopupReady === 'function') { tbb.onBeforePopupReady.call(this); } resizePopupDelayed(); let body = win.document.body; body.removeAttribute('data-resize-popup'); let mutationObserver = new win.MutationObserver(onResizeRequested); mutationObserver.observe(body, { attributes: true, attributeFilter: [ 'data-resize-popup' ] }); }; iframe.addEventListener('load', onPopupReady, true); }; })(); /******************************************************************************/ (function () { // Add toolbar button for not-Basilisk if (Services.appinfo.ID === "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}") { return; } let tbb = vAPI.toolbarButton; if (tbb.init !== null) { return; } tbb.codePath = 'legacy'; tbb.viewId = tbb.id + '-panel'; let styleSheetUri = null; let createToolbarButton = function (window) { let document = window.document; let toolbarButton = document.createElement('toolbarbutton'); toolbarButton.setAttribute('id', tbb.id); // type = panel would be more accurate, but doesn't look as good toolbarButton.setAttribute('type', 'menu'); toolbarButton.setAttribute('removable', 'true'); toolbarButton.setAttribute('class', 'toolbarbutton-1 ' +'chromeclass-toolbar-additional'); toolbarButton.setAttribute('label', tbb.label); toolbarButton.setAttribute('tooltiptext', tbb.tooltiptext); let toolbarButtonPanel = document.createElement('panel'); // NOTE: Setting level to parent breaks the popup for PaleMoon under // linux (mouse pointer misaligned with content). For some reason. // eMatrix: TODO check if it's still true // toolbarButtonPanel.setAttribute('level', 'parent'); tbb.populatePanel(document, toolbarButtonPanel); toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing); toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding); toolbarButton.appendChild(toolbarButtonPanel); toolbarButtonPanel.setAttribute('tooltiptext', ''); return toolbarButton; }; let addLegacyToolbarButton = function (window) { // eMatrix's stylesheet lazily added. if (styleSheetUri === null) { var sss = Cc["@mozilla.org/content/style-sheet-service;1"] .getService(Ci.nsIStyleSheetService); styleSheetUri = Services.io .newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null); // Register global so it works in all windows, including palette if (!sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET)) { sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET); } } let document = window.document; // https://github.com/gorhill/uMatrix/issues/357 // Already installed? if (document.getElementById(tbb.id) !== null) { return; } let toolbox = document.getElementById('navigator-toolbox') || document.getElementById('mail-toolbox'); if (toolbox === null) { return; } let toolbarButton = createToolbarButton(window); let palette = toolbox.palette; if (palette && palette.querySelector('#' + tbb.id) === null) { palette.appendChild(toolbarButton); } // Find the place to put the button. // Pale Moon: `toolbox.externalToolbars` can be // undefined. Seen while testing popup test number 3: // http://raymondhill.net/ublock/popup.html let toolbars = toolbox.externalToolbars ? toolbox.externalToolbars.slice() : []; for (let child of toolbox.children) { if (child.localName === 'toolbar') { toolbars.push(child); } } for (let toolbar of toolbars) { let currentsetString = toolbar.getAttribute('currentset'); if (!currentsetString) { continue; } let currentset = currentsetString.split(/\s*,\s*/); let index = currentset.indexOf(tbb.id); if (index === -1) { continue; } // This can occur with Pale Moon: // "TypeError: toolbar.insertItem is not a function" if (typeof toolbar.insertItem !== 'function') { continue; } // Found our button on this toolbar - but where on it? let before = null; for (let i = index+1; i iframe {', 'height: 290px;', 'max-width: none !important;', 'min-width: 0 !important;', 'overflow: hidden !important;', 'padding: 0 !important;', 'width: 160px;', '}' ]; styleURI = Services.io.newURI('data:text/css,' +encodeURIComponent(style.join('')), null, null); CustomizableUI.createWidget(this); vAPI.addCleanUpTask(shutdown); }; })(); // No toolbar button. (function () { // Just to ensure the number of cleanup tasks is as expected: toolbar // button code is one single cleanup task regardless of platform. // eMatrix: might not be needed anymore if (vAPI.toolbarButton.init === null) { vAPI.addCleanUpTask(function(){}); } })(); if (vAPI.toolbarButton.init !== null) { vAPI.toolbarButton.init(); } vAPI.contextMenu = { contextMap: { frame: 'inFrame', link: 'onLink', image: 'onImage', audio: 'onAudio', video: 'onVideo', editable: 'onEditableArea' } }; vAPI.contextMenu.displayMenuItem = function ({target}) { let doc = target.ownerDocument; let gContextMenu = doc.defaultView.gContextMenu; if (!gContextMenu.browser) { return; } let menuitem = doc.getElementById(vAPI.contextMenu.menuItemId); let currentURI = gContextMenu.browser.currentURI; // https://github.com/chrisaljoudi/uBlock/issues/105 // TODO: Should the element picker works on any kind of pages? if (!currentURI.schemeIs('http') && !currentURI.schemeIs('https')) { menuitem.setAttribute('hidden', true); return; } let ctx = vAPI.contextMenu.contexts; if (!ctx) { menuitem.setAttribute('hidden', false); return; } let ctxMap = vAPI.contextMenu.contextMap; for (let context of ctx) { if (context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage && !gContextMenu.onEditableArea && !gContextMenu.inFrame && !gContextMenu.onVideo && !gContextMenu.onAudio) { menuitem.setAttribute('hidden', false); return; } if (ctxMap.hasOwnProperty(context) && gContextMenu[ctxMap[context]]) { menuitem.setAttribute('hidden', false); return; } } menuitem.setAttribute('hidden', true); }; vAPI.contextMenu.register = (function () { let register = function (doc) { if (!this.menuItemId) { return; } // Already installed? if (doc.getElementById(this.menuItemId) !== null) { return; } let contextMenu = doc.getElementById('contentAreaContextMenu'); let menuitem = doc.createElement('menuitem'); menuitem.setAttribute('id', this.menuItemId); menuitem.setAttribute('label', this.menuLabel); menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png')); menuitem.setAttribute('class', 'menuitem-iconic'); menuitem.addEventListener('command', this.onCommand); contextMenu.addEventListener('popupshowing', this.displayMenuItem); contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator')); }; var registerSafely = function (doc, tryCount) { // https://github.com/gorhill/uBlock/issues/906 // Be sure document.readyState is 'complete': it could happen // at launch time that we are called by // vAPI.contextMenu.create() directly before the environment // is properly initialized. if (doc.readyState === 'complete') { register.call(this, doc); return; } if (typeof tryCount !== 'number') { tryCount = 0; } tryCount += 1; if ( tryCount < 8) { vAPI.setTimeout(registerSafely.bind(this, doc, tryCount), 200); } }; return registerSafely; })(); vAPI.contextMenu.unregister = function (doc) { if (!this.menuItemId) { return; } let menuitem = doc.getElementById(this.menuItemId); if (menuitem === null) { return; } let contextMenu = menuitem.parentNode; menuitem.removeEventListener('command', this.onCommand); contextMenu.removeEventListener('popupshowing', this.displayMenuItem); contextMenu.removeChild(menuitem); }; vAPI.contextMenu.create = function (details, callback) { this.menuItemId = details.id; this.menuLabel = details.title; this.contexts = details.contexts; if (Array.isArray(this.contexts) && this.contexts.length) { this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null; } else { // default in Chrome this.contexts = ['page']; } this.onCommand = function () { let gContextMenu = vAPI.browser.getOwnerWindow(this).gContextMenu; let details = { menuItemId: this.id }; if (gContextMenu.inFrame) { details.tagName = 'iframe'; // Probably won't work with e10s // eMatrix: doesn't matter ;) details.frameUrl = gContextMenu.focusedWindow.location.href; } else if (gContextMenu.onImage) { details.tagName = 'img'; details.srcUrl = gContextMenu.mediaURL; } else if (gContextMenu.onAudio) { details.tagName = 'audio'; details.srcUrl = gContextMenu.mediaURL; } else if (gContextMenu.onVideo) { details.tagName = 'video'; details.srcUrl = gContextMenu.mediaURL; } else if (gContextMenu.onLink) { details.tagName = 'a'; details.linkUrl = gContextMenu.linkURL; } callback(details, { id: vAPI.tabs.manager.tabIdFromTarget(gContextMenu.browser), url: gContextMenu.browser.currentURI.asciiSpec }); }; for (let win of vAPI.window.getWindows()) { this.register(win.document); } }; vAPI.contextMenu.remove = function () { for (let win of vAPI.window.getWindows()) { this.unregister(win.document); } this.menuItemId = null; this.menuLabel = null; this.contexts = null; this.onCommand = null; }; let optionsObserver = (function () { let addonId = 'eMatrix@vannilla.org'; let commandHandler = function () { switch (this.id) { case 'showDashboardButton': vAPI.tabs.open({ url: 'dashboard.html', index: -1, }); break; case 'showLoggerButton': vAPI.tabs.open({ url: 'logger-ui.html', index: -1, }); break; default: break; } }; let setupOptionsButton = function (doc, id) { let button = doc.getElementById(id); if (button === null) { return; } button.addEventListener('command', commandHandler); button.label = vAPI.i18n(id); }; let setupOptionsButtons = function (doc) { setupOptionsButton(doc, 'showDashboardButton'); setupOptionsButton(doc, 'showLoggerButton'); }; let observer = { observe: function (doc, topic, id) { if (id !== addonId) { return; } setupOptionsButtons(doc); } }; var canInit = function() { // https://github.com/gorhill/uBlock/issues/948 // Older versions of Firefox can throw here when looking // up `currentURI`. try { let tabBrowser = vAPI.tabs.manager.currentBrowser(); return tabBrowser && tabBrowser.currentURI && tabBrowser.currentURI.spec === 'about:addons' && tabBrowser.contentDocument && tabBrowser.contentDocument.readyState === 'complete'; } catch (ex) { // Ignore } }; // Manually add the buttons if the `about:addons` page is // already opened. let init = function () { if (canInit()) { setupOptionsButtons(vAPI.tabs.manager .currentBrowser().contentDocument); } }; let unregister = function () { Services.obs.removeObserver(observer, 'addon-options-displayed'); }; let register = function () { Services.obs.addObserver(observer, 'addon-options-displayed', false); vAPI.addCleanUpTask(unregister); vAPI.deferUntil(canInit, init, { next: 463 }); }; return { register: register, unregister: unregister }; })(); optionsObserver.register(); vAPI.onLoadAllCompleted = function() { // This is called only once, when everything has been loaded // in memory after the extension was launched. It can be used // to inject content scripts in already opened web pages, to // remove whatever nuisance could make it to the web pages // before uBlock was ready. for (let browser of vAPI.tabs.manager.browsers()) { browser.messageManager .sendAsyncMessage(location.host + '-load-completed'); } }; // Likelihood is that we do not have to punycode: given punycode overhead, // it's faster to check and skip than do it unconditionally all the time. var punycodeHostname = punycode.toASCII; var isNotASCII = /[^\x21-\x7F]/; vAPI.punycodeHostname = function (hostname) { return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname; }; vAPI.punycodeURL = function (url) { if (isNotASCII.test(url)) { return Services.io.newURI(url, null, null).asciiSpec; } return url; }; vAPI.cloud = (function () { let extensionBranchPath = 'extensions.' + location.host; let cloudBranchPath = extensionBranchPath + '.cloudStorage'; // https://github.com/gorhill/uBlock/issues/80#issuecomment-132081658 // We must use get/setComplexValue in order to properly handle strings // with unicode characters. let iss = Ci.nsISupportsString; let argstr = Components.classes['@mozilla.org/supports-string;1'] .createInstance(iss); let options = { defaultDeviceName: '', deviceName: '' }; // User-supplied device name. try { options.deviceName = Services.prefs .getBranch(extensionBranchPath + '.') .getComplexValue('deviceName', iss) .data; } catch(ex) { // Ignore } var getDefaultDeviceName = function() { var name = ''; try { name = Services.prefs .getBranch('services.sync.client.') .getComplexValue('name', iss) .data; } catch(ex) { // Ignore } return name || window.navigator.platform || window.navigator.oscpu; }; let start = function (dataKeys) { let extensionBranch = Services.prefs.getBranch(extensionBranchPath + '.'); let syncBranch = Services.prefs.getBranch('services.sync.prefs.sync.'); // Mark config entries as syncable argstr.data = ''; let dataKey; for (let i=0; i