You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2915 lines
89 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
  1. /*******************************************************************************
  2. µBlock - a browser extension to block requests.
  3. Copyright (C) 2014 The µBlock authors
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see {http://www.gnu.org/licenses/}.
  14. Home: https://github.com/gorhill/uMatrix
  15. */
  16. /* jshint bitwise: false, boss: true, esnext: true */
  17. /* global self, Components, punycode, µBlock */
  18. // For background page
  19. /******************************************************************************/
  20. (function() {
  21. 'use strict';
  22. /******************************************************************************/
  23. // Useful links
  24. //
  25. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface
  26. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Services.jsm
  27. /******************************************************************************/
  28. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  29. const {Services} = Cu.import('resource://gre/modules/Services.jsm', null);
  30. /******************************************************************************/
  31. var vAPI = self.vAPI = self.vAPI || {};
  32. vAPI.firefox = true;
  33. /******************************************************************************/
  34. vAPI.app = {
  35. name: 'uMatrix',
  36. version: location.hash.slice(1)
  37. };
  38. /******************************************************************************/
  39. vAPI.app.start = function() {
  40. };
  41. /******************************************************************************/
  42. vAPI.app.stop = function() {
  43. };
  44. /******************************************************************************/
  45. vAPI.app.restart = function() {
  46. // Listening in bootstrap.js
  47. Cc['@mozilla.org/childprocessmessagemanager;1']
  48. .getService(Ci.nsIMessageSender)
  49. .sendAsyncMessage(location.host + '-restart');
  50. };
  51. /******************************************************************************/
  52. // https://stackoverflow.com/questions/6715571/how-to-get-result-of-console-trace-as-string-in-javascript-with-chrome-or-fire/28118170#28118170
  53. /*
  54. function logStackTrace(msg) {
  55. var stack;
  56. try {
  57. throw new Error('');
  58. }
  59. catch (error) {
  60. stack = error.stack || '';
  61. }
  62. stack = stack.split('\n').map(function(line) { return line.trim(); });
  63. stack.shift();
  64. if ( msg ) {
  65. stack.unshift(msg);
  66. }
  67. console.log(stack.join('\n'));
  68. }
  69. */
  70. /******************************************************************************/
  71. // List of things that needs to be destroyed when disabling the extension
  72. // Only functions should be added to it
  73. var cleanupTasks = [];
  74. // This must be updated manually, every time a new task is added/removed
  75. // Fixed by github.com/AlexVallat:
  76. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  77. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  78. var expectedNumberOfCleanups = 7;
  79. window.addEventListener('unload', function() {
  80. if ( typeof vAPI.app.onShutdown === 'function' ) {
  81. vAPI.app.onShutdown();
  82. }
  83. for ( var cleanup of cleanupTasks ) {
  84. cleanup();
  85. }
  86. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  87. console.error(
  88. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  89. cleanupTasks.length,
  90. expectedNumberOfCleanups
  91. );
  92. }
  93. // frameModule needs to be cleared too
  94. var frameModule = {};
  95. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  96. frameModule.contentObserver.unregister();
  97. Cu.unload(vAPI.getURL('frameModule.js'));
  98. });
  99. /******************************************************************************/
  100. // For now, only booleans.
  101. vAPI.browserSettings = {
  102. originalValues: {},
  103. rememberOriginalValue: function(branch, setting) {
  104. var key = branch + '.' + setting;
  105. if ( this.originalValues.hasOwnProperty(key) ) {
  106. return;
  107. }
  108. var hasUserValue = false;
  109. try {
  110. hasUserValue = Services.prefs.getBranch(branch + '.').prefHasUserValue(setting);
  111. } catch (ex) {
  112. }
  113. this.originalValues[key] = hasUserValue ? this.getBool(branch, setting) : undefined;
  114. },
  115. clear: function(branch, setting) {
  116. var key = branch + '.' + setting;
  117. // Value was not overriden -- nothing to restore
  118. if ( this.originalValues.hasOwnProperty(key) === false ) {
  119. return;
  120. }
  121. var value = this.originalValues[key];
  122. // https://github.com/gorhill/uBlock/issues/292#issuecomment-109621979
  123. // Forget the value immediately, it may change outside of
  124. // uBlock control.
  125. delete this.originalValues[key];
  126. // Original value was a default one
  127. if ( value === undefined ) {
  128. try {
  129. Services.prefs.getBranch(branch + '.').clearUserPref(setting);
  130. } catch (ex) {
  131. }
  132. return;
  133. }
  134. // Current value is same as original
  135. if ( this.getBool(branch, setting) === value ) {
  136. return;
  137. }
  138. // Reset to original value
  139. try {
  140. Services.prefs.getBranch(branch + '.').setBoolPref(setting, value);
  141. } catch (ex) {
  142. }
  143. },
  144. getBool: function(branch, setting) {
  145. try {
  146. return Services.prefs.getBranch(branch + '.').getBoolPref(setting);
  147. } catch (ex) {
  148. }
  149. return undefined;
  150. },
  151. setBool: function(branch, setting, value) {
  152. try {
  153. Services.prefs.getBranch(branch + '.').setBoolPref(setting, value);
  154. } catch (ex) {
  155. }
  156. },
  157. set: function(details) {
  158. var value;
  159. for ( var setting in details ) {
  160. if ( details.hasOwnProperty(setting) === false ) {
  161. continue;
  162. }
  163. switch ( setting ) {
  164. case 'prefetching':
  165. this.rememberOriginalValue('network', 'prefetch-next');
  166. value = !!details[setting];
  167. // https://github.com/gorhill/uBlock/issues/292
  168. // "true" means "do not disable", i.e. leave entry alone
  169. if ( value === true ) {
  170. this.clear('network', 'prefetch-next');
  171. } else {
  172. this.setBool('network', 'prefetch-next', false);
  173. }
  174. break;
  175. case 'hyperlinkAuditing':
  176. this.rememberOriginalValue('browser', 'send_pings');
  177. this.rememberOriginalValue('beacon', 'enabled');
  178. value = !!details[setting];
  179. // https://github.com/gorhill/uBlock/issues/292
  180. // "true" means "do not disable", i.e. leave entry alone
  181. if ( value === true ) {
  182. this.clear('browser', 'send_pings');
  183. this.clear('beacon', 'enabled');
  184. } else {
  185. this.setBool('browser', 'send_pings', false);
  186. this.setBool('beacon', 'enabled', false);
  187. }
  188. break;
  189. case 'webrtcIPAddress':
  190. this.rememberOriginalValue('media.peerconnection', 'enabled');
  191. value = !!details[setting];
  192. if ( value === true ) {
  193. this.clear('media.peerconnection', 'enabled');
  194. } else {
  195. this.setBool('media.peerconnection', 'enabled', false);
  196. }
  197. break;
  198. default:
  199. break;
  200. }
  201. }
  202. },
  203. restoreAll: function() {
  204. var pos;
  205. for ( var key in this.originalValues ) {
  206. if ( this.originalValues.hasOwnProperty(key) === false ) {
  207. continue;
  208. }
  209. pos = key.lastIndexOf('.');
  210. this.clear(key.slice(0, pos), key.slice(pos + 1));
  211. }
  212. }
  213. };
  214. cleanupTasks.push(vAPI.browserSettings.restoreAll.bind(vAPI.browserSettings));
  215. /******************************************************************************/
  216. // API matches that of chrome.storage.local:
  217. // https://developer.chrome.com/extensions/storage
  218. vAPI.storage = (function() {
  219. var db = null;
  220. var vacuumTimer = null;
  221. var close = function() {
  222. if ( vacuumTimer !== null ) {
  223. clearTimeout(vacuumTimer);
  224. vacuumTimer = null;
  225. }
  226. if ( db === null ) {
  227. return;
  228. }
  229. db.asyncClose();
  230. db = null;
  231. };
  232. var open = function() {
  233. if ( db !== null ) {
  234. return db;
  235. }
  236. // Create path
  237. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  238. path.append('extension-data');
  239. if ( !path.exists() ) {
  240. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  241. }
  242. if ( !path.isDirectory() ) {
  243. throw Error('Should be a directory...');
  244. }
  245. path.append(location.host + '.sqlite');
  246. // Open database
  247. try {
  248. db = Services.storage.openDatabase(path);
  249. if ( db.connectionReady === false ) {
  250. db.asyncClose();
  251. db = null;
  252. }
  253. } catch (ex) {
  254. }
  255. if ( db === null ) {
  256. return null;
  257. }
  258. // Database was opened, register cleanup task
  259. cleanupTasks.push(close);
  260. // Setup database
  261. db.createAsyncStatement('CREATE TABLE IF NOT EXISTS "settings" ("name" TEXT PRIMARY KEY NOT NULL, "value" TEXT);')
  262. .executeAsync();
  263. if ( vacuum !== null ) {
  264. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  265. }
  266. return db;
  267. };
  268. // https://developer.mozilla.org/en-US/docs/Storage/Performance#Vacuuming_and_zero-fill
  269. // Vacuum only once, and only while idle
  270. var vacuum = function() {
  271. vacuumTimer = null;
  272. if ( db === null ) {
  273. return;
  274. }
  275. var idleSvc = Cc['@mozilla.org/widget/idleservice;1']
  276. .getService(Ci.nsIIdleService);
  277. if ( idleSvc.idleTime < 60000 ) {
  278. vacuumTimer = vAPI.setTimeout(vacuum, 60000);
  279. return;
  280. }
  281. db.createAsyncStatement('VACUUM').executeAsync();
  282. vacuum = null;
  283. };
  284. // Execute a query
  285. var runStatement = function(stmt, callback) {
  286. var result = {};
  287. stmt.executeAsync({
  288. handleResult: function(rows) {
  289. if ( !rows || typeof callback !== 'function' ) {
  290. return;
  291. }
  292. var row;
  293. while ( row = rows.getNextRow() ) {
  294. // we assume that there will be two columns, since we're
  295. // using it only for preferences
  296. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  297. }
  298. },
  299. handleCompletion: function(reason) {
  300. if ( typeof callback === 'function' && reason === 0 ) {
  301. callback(result);
  302. }
  303. },
  304. handleError: function(error) {
  305. console.error('SQLite error ', error.result, error.message);
  306. // Caller expects an answer regardless of failure.
  307. if ( typeof callback === 'function' ) {
  308. callback(null);
  309. }
  310. }
  311. });
  312. };
  313. var bindNames = function(stmt, names) {
  314. if ( Array.isArray(names) === false || names.length === 0 ) {
  315. return;
  316. }
  317. var params = stmt.newBindingParamsArray();
  318. var i = names.length, bp;
  319. while ( i-- ) {
  320. bp = params.newBindingParams();
  321. bp.bindByName('name', names[i]);
  322. params.addParams(bp);
  323. }
  324. stmt.bindParameters(params);
  325. };
  326. var clear = function(callback) {
  327. if ( open() === null ) {
  328. if ( typeof callback === 'function' ) {
  329. callback();
  330. }
  331. return;
  332. }
  333. runStatement(db.createAsyncStatement('DELETE FROM "settings";'), callback);
  334. };
  335. var getBytesInUse = function(keys, callback) {
  336. if ( typeof callback !== 'function' ) {
  337. return;
  338. }
  339. if ( open() === null ) {
  340. callback(0);
  341. return;
  342. }
  343. var stmt;
  344. if ( Array.isArray(keys) ) {
  345. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings" WHERE "name" = :name');
  346. bindNames(keys);
  347. } else {
  348. stmt = db.createAsyncStatement('SELECT "size" AS "size", SUM(LENGTH("value")) FROM "settings"');
  349. }
  350. runStatement(stmt, function(result) {
  351. callback(result.size);
  352. });
  353. };
  354. var read = function(details, callback) {
  355. if ( typeof callback !== 'function' ) {
  356. return;
  357. }
  358. var prepareResult = function(result) {
  359. var key;
  360. for ( key in result ) {
  361. if ( result.hasOwnProperty(key) === false ) {
  362. continue;
  363. }
  364. result[key] = JSON.parse(result[key]);
  365. }
  366. if ( typeof details === 'object' && details !== null ) {
  367. for ( key in details ) {
  368. if ( result.hasOwnProperty(key) === false ) {
  369. result[key] = details[key];
  370. }
  371. }
  372. }
  373. callback(result);
  374. };
  375. if ( open() === null ) {
  376. prepareResult({});
  377. return;
  378. }
  379. var names = [];
  380. if ( details !== null ) {
  381. if ( Array.isArray(details) ) {
  382. names = details;
  383. } else if ( typeof details === 'object' ) {
  384. names = Object.keys(details);
  385. } else {
  386. names = [details.toString()];
  387. }
  388. }
  389. var stmt;
  390. if ( names.length === 0 ) {
  391. stmt = db.createAsyncStatement('SELECT * FROM "settings"');
  392. } else {
  393. stmt = db.createAsyncStatement('SELECT * FROM "settings" WHERE "name" = :name');
  394. bindNames(stmt, names);
  395. }
  396. runStatement(stmt, prepareResult);
  397. };
  398. var remove = function(keys, callback) {
  399. if ( open() === null ) {
  400. if ( typeof callback === 'function' ) {
  401. callback();
  402. }
  403. return;
  404. }
  405. var stmt = db.createAsyncStatement('DELETE FROM "settings" WHERE "name" = :name');
  406. bindNames(stmt, typeof keys === 'string' ? [keys] : keys);
  407. runStatement(stmt, callback);
  408. };
  409. var write = function(details, callback) {
  410. if ( open() === null ) {
  411. if ( typeof callback === 'function' ) {
  412. callback();
  413. }
  414. return;
  415. }
  416. var stmt = db.createAsyncStatement('INSERT OR REPLACE INTO "settings" ("name", "value") VALUES(:name, :value)');
  417. var params = stmt.newBindingParamsArray(), bp;
  418. for ( var key in details ) {
  419. if ( details.hasOwnProperty(key) === false ) {
  420. continue;
  421. }
  422. bp = params.newBindingParams();
  423. bp.bindByName('name', key);
  424. bp.bindByName('value', JSON.stringify(details[key]));
  425. params.addParams(bp);
  426. }
  427. if ( params.length === 0 ) {
  428. return;
  429. }
  430. stmt.bindParameters(params);
  431. runStatement(stmt, callback);
  432. };
  433. // Export API
  434. var api = {
  435. QUOTA_BYTES: 100 * 1024 * 1024,
  436. clear: clear,
  437. get: read,
  438. getBytesInUse: getBytesInUse,
  439. remove: remove,
  440. set: write
  441. };
  442. return api;
  443. })();
  444. /******************************************************************************/
  445. var getTabBrowser = function(win) {
  446. return win.gBrowser || null;
  447. };
  448. /******************************************************************************/
  449. var getOwnerWindow = function(target) {
  450. if ( target.ownerDocument ) {
  451. return target.ownerDocument.defaultView;
  452. }
  453. return null;
  454. };
  455. /******************************************************************************/
  456. vAPI.isBehindTheSceneTabId = function(tabId) {
  457. return tabId.toString() === '-1';
  458. };
  459. vAPI.noTabId = '-1';
  460. /******************************************************************************/
  461. vAPI.tabs = {};
  462. /******************************************************************************/
  463. vAPI.tabs.registerListeners = function() {
  464. tabWatcher.start();
  465. };
  466. /******************************************************************************/
  467. vAPI.tabs.get = function(tabId, callback) {
  468. var browser;
  469. if ( tabId === null ) {
  470. browser = tabWatcher.currentBrowser();
  471. tabId = tabWatcher.tabIdFromTarget(browser);
  472. } else {
  473. browser = tabWatcher.browserFromTabId(tabId);
  474. }
  475. // For internal use
  476. if ( typeof callback !== 'function' ) {
  477. return browser;
  478. }
  479. if ( !browser ) {
  480. callback();
  481. return;
  482. }
  483. var win = getOwnerWindow(browser);
  484. var tabBrowser = getTabBrowser(win);
  485. var windows = this.getWindows();
  486. callback({
  487. id: tabId,
  488. index: tabWatcher.indexFromTarget(browser),
  489. windowId: windows.indexOf(win),
  490. active: browser === tabBrowser.selectedBrowser,
  491. url: browser.currentURI.asciiSpec,
  492. title: browser.contentTitle
  493. });
  494. };
  495. /******************************************************************************/
  496. vAPI.tabs.getAllSync = function(window) {
  497. var win, tab;
  498. var tabs = [];
  499. for ( win of this.getWindows() ) {
  500. if ( window && window !== win ) {
  501. continue;
  502. }
  503. var tabBrowser = getTabBrowser(win);
  504. if ( tabBrowser === null ) {
  505. continue;
  506. }
  507. for ( tab of tabBrowser.tabs ) {
  508. tabs.push(tab);
  509. }
  510. }
  511. return tabs;
  512. };
  513. /******************************************************************************/
  514. vAPI.tabs.getAll = function(callback) {
  515. var tabs = [], tab;
  516. for ( var browser of tabWatcher.browsers() ) {
  517. tab = tabWatcher.tabFromBrowser(browser);
  518. if ( tab === null ) {
  519. continue;
  520. }
  521. if ( tab.hasAttribute('pending') ) {
  522. continue;
  523. }
  524. tabs.push({
  525. id: tabWatcher.tabIdFromTarget(browser),
  526. url: browser.currentURI.asciiSpec
  527. });
  528. }
  529. callback(tabs);
  530. };
  531. /******************************************************************************/
  532. vAPI.tabs.getWindows = function() {
  533. var winumerator = Services.wm.getEnumerator('navigator:browser');
  534. var windows = [];
  535. while ( winumerator.hasMoreElements() ) {
  536. var win = winumerator.getNext();
  537. if ( !win.closed ) {
  538. windows.push(win);
  539. }
  540. }
  541. return windows;
  542. };
  543. /******************************************************************************/
  544. // properties of the details object:
  545. // url: 'URL', // the address that will be opened
  546. // tabId: 1, // the tab is used if set, instead of creating a new one
  547. // index: -1, // undefined: end of the list, -1: following tab, or after index
  548. // active: false, // opens the tab in background - true and undefined: foreground
  549. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  550. vAPI.tabs.open = function(details) {
  551. if ( !details.url ) {
  552. return null;
  553. }
  554. // extension pages
  555. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  556. details.url = vAPI.getURL(details.url);
  557. }
  558. var tab;
  559. if ( details.select ) {
  560. var URI = Services.io.newURI(details.url, null, null);
  561. for ( tab of this.getAllSync() ) {
  562. var browser = tabWatcher.browserFromTarget(tab);
  563. // Or simply .equals if we care about the fragment
  564. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  565. continue;
  566. }
  567. this.select(tab);
  568. return;
  569. }
  570. }
  571. if ( details.active === undefined ) {
  572. details.active = true;
  573. }
  574. if ( details.tabId ) {
  575. tab = tabWatcher.browserFromTabId(details.tabId);
  576. if ( tab ) {
  577. tabWatcher.browserFromTarget(tab).loadURI(details.url);
  578. return;
  579. }
  580. }
  581. var win = Services.wm.getMostRecentWindow('navigator:browser');
  582. var tabBrowser = getTabBrowser(win);
  583. // Open in a standalone window
  584. if ( details.popup === true ) {
  585. Services.ww.openWindow(
  586. self,
  587. details.url,
  588. null,
  589. 'menubar=no,toolbar=no,location=no,resizable=yes',
  590. null
  591. );
  592. return;
  593. }
  594. if ( details.index === -1 ) {
  595. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  596. }
  597. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  598. if ( details.index !== undefined ) {
  599. tabBrowser.moveTabTo(tab, details.index);
  600. }
  601. };
  602. /******************************************************************************/
  603. // Replace the URL of a tab. Noop if the tab does not exist.
  604. vAPI.tabs.replace = function(tabId, url) {
  605. var targetURL = url;
  606. // extension pages
  607. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  608. targetURL = vAPI.getURL(targetURL);
  609. }
  610. var browser = tabWatcher.browserFromTabId(tabId);
  611. if ( browser ) {
  612. browser.loadURI(targetURL);
  613. }
  614. };
  615. /******************************************************************************/
  616. vAPI.tabs._remove = function(tab, tabBrowser) {
  617. tabBrowser.removeTab(tab);
  618. };
  619. /******************************************************************************/
  620. vAPI.tabs.remove = function(tabId) {
  621. var browser = tabWatcher.browserFromTabId(tabId);
  622. if ( !browser ) {
  623. return;
  624. }
  625. var tab = tabWatcher.tabFromBrowser(browser);
  626. if ( !tab ) {
  627. return;
  628. }
  629. this._remove(tab, getTabBrowser(getOwnerWindow(browser)));
  630. };
  631. /******************************************************************************/
  632. vAPI.tabs.reload = function(tabId) {
  633. var browser = tabWatcher.browserFromTabId(tabId);
  634. if ( !browser ) {
  635. return;
  636. }
  637. browser.webNavigation.reload(Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE);
  638. };
  639. /******************************************************************************/
  640. vAPI.tabs.select = function(tab) {
  641. if ( typeof tab !== 'object' ) {
  642. tab = tabWatcher.tabFromBrowser(tabWatcher.browserFromTabId(tab));
  643. }
  644. if ( !tab ) {
  645. return;
  646. }
  647. // https://github.com/gorhill/uBlock/issues/470
  648. var win = getOwnerWindow(tab);
  649. win.focus();
  650. var tabBrowser = getTabBrowser(win);
  651. tabBrowser.selectedTab = tab;
  652. };
  653. /******************************************************************************/
  654. vAPI.tabs.injectScript = function(tabId, details, callback) {
  655. var browser = tabWatcher.browserFromTabId(tabId);
  656. if ( !browser ) {
  657. return;
  658. }
  659. if ( typeof details.file !== 'string' ) {
  660. return;
  661. }
  662. details.file = vAPI.getURL(details.file);
  663. browser.messageManager.sendAsyncMessage(
  664. location.host + ':broadcast',
  665. JSON.stringify({
  666. broadcast: true,
  667. channelName: 'vAPI',
  668. msg: {
  669. cmd: 'injectScript',
  670. details: details
  671. }
  672. })
  673. );
  674. if ( typeof callback === 'function' ) {
  675. vAPI.setTimeout(callback, 13);
  676. }
  677. };
  678. /******************************************************************************/
  679. // Firefox:
  680. // https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser
  681. //
  682. // browser --> ownerDocument --> defaultView --> gBrowser --> browsers --+
  683. // ^ |
  684. // | |
  685. // +-------------------------------------------------------------------
  686. //
  687. // browser (browser)
  688. // contentTitle
  689. // currentURI
  690. // ownerDocument (XULDocument)
  691. // defaultView (ChromeWindow)
  692. // gBrowser (tabbrowser OR browser)
  693. // browsers (browser)
  694. // selectedBrowser
  695. // selectedTab
  696. // tabs (tab.tabbrowser-tab)
  697. //
  698. // Fennec: (what I figured so far)
  699. //
  700. // tab --> browser windows --> window --> BrowserApp --> tabs --+
  701. // ^ window |
  702. // | |
  703. // +---------------------------------------------------------------+
  704. //
  705. // tab
  706. // browser
  707. // [manual search to go back to tab from list of windows]
  708. var tabWatcher = (function() {
  709. // TODO: find out whether we need a janitor to take care of stale entries.
  710. var browserToTabIdMap = new Map();
  711. var tabIdToBrowserMap = new Map();
  712. var tabIdGenerator = 1;
  713. var indexFromBrowser = function(browser) {
  714. var win = getOwnerWindow(browser);
  715. if ( !win ) {
  716. return -1;
  717. }
  718. var tabbrowser = getTabBrowser(win);
  719. if ( !tabbrowser ) {
  720. return -1;
  721. }
  722. // This can happen, for example, the `view-source:` window, there is
  723. // no tabbrowser object, the browser object sits directly in the
  724. // window.
  725. if ( tabbrowser === browser ) {
  726. return 0;
  727. }
  728. // Fennec
  729. // https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/API/BrowserApp
  730. if ( vAPI.fennec ) {
  731. return tabbrowser.tabs.indexOf(tabbrowser.getTabForBrowser(browser));
  732. }
  733. return tabbrowser.browsers.indexOf(browser);
  734. };
  735. var indexFromTarget = function(target) {
  736. return indexFromBrowser(browserFromTarget(target));
  737. };
  738. var tabFromBrowser = function(browser) {
  739. var i = indexFromBrowser(browser);
  740. if ( i === -1 ) {
  741. return null;
  742. }
  743. var win = getOwnerWindow(browser);
  744. if ( !win ) {
  745. return null;
  746. }
  747. var tabbrowser = getTabBrowser(win);
  748. if ( !tabbrowser ) {
  749. return null;
  750. }
  751. if ( !tabbrowser.tabs || i >= tabbrowser.tabs.length ) {
  752. return null;
  753. }
  754. return tabbrowser.tabs[i];
  755. };
  756. var browserFromTarget = function(target) {
  757. if ( !target ) {
  758. return null;
  759. }
  760. if ( vAPI.fennec ) {
  761. if ( target.browser ) { // target is a tab
  762. target = target.browser;
  763. }
  764. } else if ( target.linkedPanel ) { // target is a tab
  765. target = target.linkedBrowser;
  766. }
  767. if ( target.localName !== 'browser' ) {
  768. return null;
  769. }
  770. return target;
  771. };
  772. var tabIdFromTarget = function(target) {
  773. var browser = browserFromTarget(target);
  774. if ( browser === null ) {
  775. return vAPI.noTabId;
  776. }
  777. var tabId = browserToTabIdMap.get(browser);
  778. if ( tabId === undefined ) {
  779. tabId = '' + tabIdGenerator++;
  780. browserToTabIdMap.set(browser, tabId);
  781. tabIdToBrowserMap.set(tabId, browser);
  782. }
  783. return tabId;
  784. };
  785. var browserFromTabId = function(tabId) {
  786. var browser = tabIdToBrowserMap.get(tabId);
  787. if ( browser === undefined ) {
  788. return null;
  789. }
  790. // Verify that the browser is still live
  791. if ( indexFromBrowser(browser) !== -1 ) {
  792. return browser;
  793. }
  794. removeBrowserEntry(tabId, browser);
  795. return null;
  796. };
  797. var currentBrowser = function() {
  798. var win = Services.wm.getMostRecentWindow('navigator:browser');
  799. // https://github.com/gorhill/uBlock/issues/399
  800. // getTabBrowser() can return null at browser launch time.
  801. var tabBrowser = getTabBrowser(win);
  802. if ( tabBrowser === null ) {
  803. return null;
  804. }
  805. return browserFromTarget(tabBrowser.selectedTab);
  806. };
  807. var removeBrowserEntry = function(tabId, browser) {
  808. if ( tabId && tabId !== vAPI.noTabId ) {
  809. vAPI.tabs.onClosed(tabId);
  810. delete vAPI.toolbarButton.tabs[tabId];
  811. tabIdToBrowserMap.delete(tabId);
  812. }
  813. if ( browser ) {
  814. browserToTabIdMap.delete(browser);
  815. }
  816. };
  817. // https://developer.mozilla.org/en-US/docs/Web/Events/TabOpen
  818. var onOpen = function({target}) {
  819. var tabId = tabIdFromTarget(target);
  820. var browser = browserFromTabId(tabId);
  821. vAPI.tabs.onNavigation({
  822. frameId: 0,
  823. tabId: tabId,
  824. url: browser.currentURI.asciiSpec,
  825. });
  826. };
  827. // https://developer.mozilla.org/en-US/docs/Web/Events/TabShow
  828. var onShow = function({target}) {
  829. tabIdFromTarget(target);
  830. };
  831. // https://developer.mozilla.org/en-US/docs/Web/Events/TabClose
  832. var onClose = function({target}) {
  833. // target is tab in Firefox, browser in Fennec
  834. var browser = browserFromTarget(target);
  835. var tabId = browserToTabIdMap.get(browser);
  836. removeBrowserEntry(tabId, browser);
  837. };
  838. // https://developer.mozilla.org/en-US/docs/Web/Events/TabSelect
  839. var onSelect = function({target}) {
  840. vAPI.setIcon(tabIdFromTarget(target), getOwnerWindow(target));
  841. };
  842. var locationChangedMessageName = location.host + ':locationChanged';
  843. var onLocationChanged = function(e) {
  844. var vapi = vAPI;
  845. var details = e.data;
  846. // Ignore notifications related to our popup
  847. if ( details.url.lastIndexOf(vapi.getURL('popup.html'), 0) === 0 ) {
  848. return;
  849. }
  850. var browser = e.target;
  851. var tabId = tabIdFromTarget(browser);
  852. if ( tabId === vapi.noTabId ) {
  853. return;
  854. }
  855. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  856. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  857. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  858. vapi.tabs.onUpdated(tabId, {url: details.url}, {
  859. frameId: 0,
  860. tabId: tabId,
  861. url: browser.currentURI.asciiSpec
  862. });
  863. return;
  864. }
  865. // https://github.com/chrisaljoudi/uBlock/issues/105
  866. // Allow any kind of pages
  867. vapi.tabs.onNavigation({
  868. frameId: 0,
  869. tabId: tabId,
  870. url: details.url,
  871. });
  872. };
  873. var attachToTabBrowser = function(window) {
  874. var tabBrowser = getTabBrowser(window);
  875. if ( !tabBrowser ) {
  876. return false;
  877. }
  878. var tabContainer = tabBrowser.tabContainer;
  879. if ( !tabContainer ) {
  880. return true;
  881. }
  882. vAPI.contextMenu.register(window.document);
  883. if ( typeof vAPI.toolbarButton.attachToNewWindow === 'function' ) {
  884. vAPI.toolbarButton.attachToNewWindow(window);
  885. }
  886. tabContainer.addEventListener('TabOpen', onOpen);
  887. tabContainer.addEventListener('TabShow', onShow);
  888. tabContainer.addEventListener('TabClose', onClose);
  889. tabContainer.addEventListener('TabSelect', onSelect);
  890. return true;
  891. };
  892. var onWindowLoad = function(ev) {
  893. if ( ev ) {
  894. this.removeEventListener(ev.type, onWindowLoad);
  895. }
  896. var wintype = this.document.documentElement.getAttribute('windowtype');
  897. if ( wintype !== 'navigator:browser' ) {
  898. return;
  899. }
  900. // On some platforms, the tab browser isn't immediately available,
  901. // try waiting a bit if this happens.
  902. var win = this;
  903. if ( attachToTabBrowser(win) === false ) {
  904. vAPI.setTimeout(attachToTabBrowser.bind(null, win), 250);
  905. }
  906. };
  907. var onWindowUnload = function() {
  908. vAPI.contextMenu.unregister(this.document);
  909. this.removeEventListener('DOMContentLoaded', onWindowLoad);
  910. var tabBrowser = getTabBrowser(this);
  911. if ( !tabBrowser ) {
  912. return;
  913. }
  914. var tabContainer = null;
  915. if ( tabBrowser.tabContainer ) {
  916. tabContainer = tabBrowser.tabContainer;
  917. }
  918. if ( tabContainer ) {
  919. tabContainer.removeEventListener('TabOpen', onOpen);
  920. tabContainer.removeEventListener('TabShow', onShow);
  921. tabContainer.removeEventListener('TabClose', onClose);
  922. tabContainer.removeEventListener('TabSelect', onSelect);
  923. }
  924. var browser, URI, tabId;
  925. for ( var tab of tabBrowser.tabs ) {
  926. browser = tabWatcher.browserFromTarget(tab);
  927. if ( browser === null ) {
  928. continue;
  929. }
  930. URI = browser.currentURI;
  931. // Close extension tabs
  932. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  933. vAPI.tabs._remove(tab, getTabBrowser(this));
  934. }
  935. browser = browserFromTarget(tab);
  936. tabId = browserToTabIdMap.get(browser);
  937. if ( tabId !== undefined ) {
  938. removeBrowserEntry(tabId, browser);
  939. tabIdToBrowserMap.delete(tabId);
  940. }
  941. browserToTabIdMap.delete(browser);
  942. }
  943. };
  944. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowWatcher
  945. var windowWatcher = {
  946. observe: function(win, topic) {
  947. if ( topic === 'domwindowopened' ) {
  948. win.addEventListener('DOMContentLoaded', onWindowLoad);
  949. return;
  950. }
  951. if ( topic === 'domwindowclosed' ) {
  952. onWindowUnload.call(win);
  953. return;
  954. }
  955. }
  956. };
  957. // Initialize map with existing active tabs
  958. var start = function() {
  959. var tabBrowser, tab;
  960. for ( var win of vAPI.tabs.getWindows() ) {
  961. onWindowLoad.call(win);
  962. tabBrowser = getTabBrowser(win);
  963. if ( tabBrowser === null ) {
  964. continue;
  965. }
  966. for ( tab of tabBrowser.tabs ) {
  967. if ( vAPI.fennec || !tab.hasAttribute('pending') ) {
  968. tabIdFromTarget(tab);
  969. }
  970. }
  971. }
  972. vAPI.messaging.globalMessageManager.addMessageListener(
  973. locationChangedMessageName,
  974. onLocationChanged
  975. );
  976. Services.ww.registerNotification(windowWatcher);
  977. };
  978. var stop = function() {
  979. vAPI.messaging.globalMessageManager.removeMessageListener(
  980. locationChangedMessageName,
  981. onLocationChanged
  982. );
  983. Services.ww.unregisterNotification(windowWatcher);
  984. for ( var win of vAPI.tabs.getWindows() ) {
  985. onWindowUnload.call(win);
  986. }
  987. browserToTabIdMap.clear();
  988. tabIdToBrowserMap.clear();
  989. };
  990. cleanupTasks.push(stop);
  991. return {
  992. browsers: function() { return browserToTabIdMap.keys(); },
  993. browserFromTabId: browserFromTabId,
  994. browserFromTarget: browserFromTarget,
  995. currentBrowser: currentBrowser,
  996. indexFromTarget: indexFromTarget,
  997. start: start,
  998. tabFromBrowser: tabFromBrowser,
  999. tabIdFromTarget: tabIdFromTarget
  1000. };
  1001. })();
  1002. /******************************************************************************/
  1003. vAPI.setIcon = function(tabId, iconId, badge) {
  1004. // If badge is undefined, then setIcon was called from the TabSelect event
  1005. var win;
  1006. if ( badge === undefined ) {
  1007. win = iconId;
  1008. } else {
  1009. win = Services.wm.getMostRecentWindow('navigator:browser');
  1010. }
  1011. var curTabId = tabWatcher.tabIdFromTarget(getTabBrowser(win).selectedTab);
  1012. var tb = vAPI.toolbarButton;
  1013. // from 'TabSelect' event
  1014. if ( tabId === undefined ) {
  1015. tabId = curTabId;
  1016. } else if ( badge !== undefined ) {
  1017. tb.tabs[tabId] = { badge: badge, img: iconId };
  1018. }
  1019. if ( tabId === curTabId ) {
  1020. tb.updateState(win, tabId);
  1021. }
  1022. };
  1023. /******************************************************************************/
  1024. vAPI.messaging = {
  1025. get globalMessageManager() {
  1026. return Cc['@mozilla.org/globalmessagemanager;1']
  1027. .getService(Ci.nsIMessageListenerManager);
  1028. },
  1029. frameScript: vAPI.getURL('frameScript.js'),
  1030. listeners: {},
  1031. defaultHandler: null,
  1032. NOOPFUNC: function(){},
  1033. UNHANDLED: 'vAPI.messaging.notHandled'
  1034. };
  1035. /******************************************************************************/
  1036. vAPI.messaging.listen = function(listenerName, callback) {
  1037. this.listeners[listenerName] = callback;
  1038. };
  1039. /******************************************************************************/
  1040. vAPI.messaging.onMessage = function({target, data}) {
  1041. var messageManager = target.messageManager;
  1042. if ( !messageManager ) {
  1043. // Message came from a popup, and its message manager is not usable.
  1044. // So instead we broadcast to the parent window.
  1045. messageManager = getOwnerWindow(
  1046. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  1047. ).messageManager;
  1048. }
  1049. var channelNameRaw = data.channelName;
  1050. var pos = channelNameRaw.indexOf('|');
  1051. var channelName = channelNameRaw.slice(pos + 1);
  1052. var callback = vAPI.messaging.NOOPFUNC;
  1053. if ( data.requestId !== undefined ) {
  1054. callback = CallbackWrapper.factory(
  1055. messageManager,
  1056. channelName,
  1057. channelNameRaw.slice(0, pos),
  1058. data.requestId
  1059. ).callback;
  1060. }
  1061. var sender = {
  1062. tab: {
  1063. id: tabWatcher.tabIdFromTarget(target)
  1064. }
  1065. };
  1066. // Specific handler
  1067. var r = vAPI.messaging.UNHANDLED;
  1068. var listener = vAPI.messaging.listeners[channelName];
  1069. if ( typeof listener === 'function' ) {
  1070. r = listener(data.msg, sender, callback);
  1071. }
  1072. if ( r !== vAPI.messaging.UNHANDLED ) {
  1073. return;
  1074. }
  1075. // Default handler
  1076. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  1077. if ( r !== vAPI.messaging.UNHANDLED ) {
  1078. return;
  1079. }
  1080. console.error('uMatrix> messaging > unknown request: %o', data);
  1081. // Unhandled:
  1082. // Need to callback anyways in case caller expected an answer, or
  1083. // else there is a memory leak on caller's side
  1084. callback();
  1085. };
  1086. /******************************************************************************/
  1087. vAPI.messaging.setup = function(defaultHandler) {
  1088. // Already setup?
  1089. if ( this.defaultHandler !== null ) {
  1090. return;
  1091. }
  1092. if ( typeof defaultHandler !== 'function' ) {
  1093. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  1094. }
  1095. this.defaultHandler = defaultHandler;
  1096. this.globalMessageManager.addMessageListener(
  1097. location.host + ':background',
  1098. this.onMessage
  1099. );
  1100. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  1101. cleanupTasks.push(function() {
  1102. var gmm = vAPI.messaging.globalMessageManager;
  1103. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  1104. gmm.removeMessageListener(
  1105. location.host + ':background',
  1106. vAPI.messaging.onMessage
  1107. );
  1108. });
  1109. };
  1110. /******************************************************************************/
  1111. vAPI.messaging.broadcast = function(message) {
  1112. this.globalMessageManager.broadcastAsyncMessage(
  1113. location.host + ':broadcast',
  1114. JSON.stringify({broadcast: true, msg: message})
  1115. );
  1116. };
  1117. /******************************************************************************/
  1118. // This allows to avoid creating a closure for every single message which
  1119. // expects an answer. Having a closure created each time a message is processed
  1120. // has been always bothering me. Another benefit of the implementation here
  1121. // is to reuse the callback proxy object, so less memory churning.
  1122. //
  1123. // https://developers.google.com/speed/articles/optimizing-javascript
  1124. // "Creating a closure is significantly slower then creating an inner
  1125. // function without a closure, and much slower than reusing a static
  1126. // function"
  1127. //
  1128. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  1129. // "the dreaded 'uniformly slow code' case where every function takes 1%
  1130. // of CPU and you have to make one hundred separate performance optimizations
  1131. // to improve performance at all"
  1132. //
  1133. // http://jsperf.com/closure-no-closure/2
  1134. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  1135. this.callback = this.proxy.bind(this); // bind once
  1136. this.init(messageManager, channelName, listenerId, requestId);
  1137. };
  1138. CallbackWrapper.junkyard = [];
  1139. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  1140. var wrapper = CallbackWrapper.junkyard.pop();
  1141. if ( wrapper ) {
  1142. wrapper.init(messageManager, channelName, listenerId, requestId);
  1143. return wrapper;
  1144. }
  1145. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  1146. };
  1147. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  1148. this.messageManager = messageManager;
  1149. this.channelName = channelName;
  1150. this.listenerId = listenerId;
  1151. this.requestId = requestId;
  1152. };
  1153. CallbackWrapper.prototype.proxy = function(response) {
  1154. var message = JSON.stringify({
  1155. requestId: this.requestId,
  1156. channelName: this.channelName,
  1157. msg: response !== undefined ? response : null
  1158. });
  1159. if ( this.messageManager.sendAsyncMessage ) {
  1160. this.messageManager.sendAsyncMessage(this.listenerId, message);
  1161. } else {
  1162. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  1163. }
  1164. // Mark for reuse
  1165. this.messageManager =
  1166. this.channelName =
  1167. this.requestId =
  1168. this.listenerId = null;
  1169. CallbackWrapper.junkyard.push(this);
  1170. };
  1171. /******************************************************************************/
  1172. var httpRequestHeadersFactory = function(channel) {
  1173. var entry = httpRequestHeadersFactory.junkyard.pop();
  1174. if ( entry ) {
  1175. return entry.init(channel);
  1176. }
  1177. return new HTTPRequestHeaders(channel);
  1178. };
  1179. httpRequestHeadersFactory.junkyard = [];
  1180. var HTTPRequestHeaders = function(channel) {
  1181. this.init(channel);
  1182. };
  1183. HTTPRequestHeaders.prototype.init = function(channel) {
  1184. this.channel = channel;
  1185. return this;
  1186. };
  1187. HTTPRequestHeaders.prototype.dispose = function() {
  1188. this.channel = null;
  1189. httpRequestHeadersFactory.junkyard.push(this);
  1190. };
  1191. HTTPRequestHeaders.prototype.getHeader = function(name) {
  1192. try {
  1193. return this.channel.getRequestHeader(name);
  1194. } catch (e) {
  1195. }
  1196. return '';
  1197. };
  1198. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  1199. var oldValue = this.getHeader(name);
  1200. if ( newValue === oldValue ) {
  1201. return false;
  1202. }
  1203. if ( oldValue === '' && create !== true ) {
  1204. return false;
  1205. }
  1206. this.channel.setRequestHeader(name, newValue, false);
  1207. return true;
  1208. };
  1209. /******************************************************************************/
  1210. var httpObserver = {
  1211. classDescription: 'net-channel-event-sinks for ' + location.host,
  1212. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  1213. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  1214. REQDATAKEY: location.host + 'reqdata',
  1215. ABORT: Components.results.NS_BINDING_ABORTED,
  1216. ACCEPT: Components.results.NS_SUCCEEDED,
  1217. // Request types:
  1218. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  1219. frameTypeMap: {
  1220. 6: 'main_frame',
  1221. 7: 'sub_frame'
  1222. },
  1223. typeMap: {
  1224. 1: 'other',
  1225. 2: 'script',
  1226. 3: 'image',
  1227. 4: 'stylesheet',
  1228. 5: 'object',
  1229. 6: 'main_frame',
  1230. 7: 'sub_frame',
  1231. 10: 'ping',
  1232. 11: 'xmlhttprequest',
  1233. 12: 'object',
  1234. 14: 'font',
  1235. 15: 'media',
  1236. 16: 'websocket',
  1237. 21: 'image'
  1238. },
  1239. mimeTypeMap: {
  1240. 'audio': 15,
  1241. 'video': 15
  1242. },
  1243. get componentRegistrar() {
  1244. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  1245. },
  1246. get categoryManager() {
  1247. return Cc['@mozilla.org/categorymanager;1']
  1248. .getService(Ci.nsICategoryManager);
  1249. },
  1250. QueryInterface: (function() {
  1251. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  1252. return XPCOMUtils.generateQI([
  1253. Ci.nsIFactory,
  1254. Ci.nsIObserver,
  1255. Ci.nsIChannelEventSink,
  1256. Ci.nsISupportsWeakReference
  1257. ]);
  1258. })(),
  1259. createInstance: function(outer, iid) {
  1260. if ( outer ) {
  1261. throw Components.results.NS_ERROR_NO_AGGREGATION;
  1262. }
  1263. return this.QueryInterface(iid);
  1264. },
  1265. register: function() {
  1266. this.pendingRingBufferInit();
  1267. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  1268. Services.obs.addObserver(this, 'http-on-opening-request', true);
  1269. Services.obs.addObserver(this, 'http-on-modify-request', true);
  1270. Services.obs.addObserver(this, 'http-on-examine-response', true);
  1271. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  1272. // Guard against stale instances not having been unregistered
  1273. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  1274. try {
  1275. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  1276. } catch (ex) {
  1277. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  1278. }
  1279. }
  1280. this.componentRegistrar.registerFactory(
  1281. this.classID,
  1282. this.classDescription,
  1283. this.contractID,
  1284. this
  1285. );
  1286. this.categoryManager.addCategoryEntry(
  1287. 'net-channel-event-sinks',
  1288. this.contractID,
  1289. this.contractID,
  1290. false,
  1291. true
  1292. );
  1293. },
  1294. unregister: function() {
  1295. Services.obs.removeObserver(this, 'http-on-opening-request');
  1296. Services.obs.removeObserver(this, 'http-on-modify-request');
  1297. Services.obs.removeObserver(this, 'http-on-examine-response');
  1298. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  1299. this.componentRegistrar.unregisterFactory(this.classID, this);
  1300. this.categoryManager.deleteCategoryEntry(
  1301. 'net-channel-event-sinks',
  1302. this.contractID,
  1303. false
  1304. );
  1305. },
  1306. PendingRequest: function() {
  1307. this.rawType = 0;
  1308. this.tabId = 0;
  1309. this._key = ''; // key is url, from URI.spec
  1310. },
  1311. // If all work fine, this map should not grow indefinitely. It can have
  1312. // stale items in it, but these will be taken care of when entries in
  1313. // the ring buffer are overwritten.
  1314. pendingURLToIndex: new Map(),
  1315. pendingWritePointer: 0,
  1316. pendingRingBuffer: new Array(32),
  1317. pendingRingBufferInit: function() {
  1318. // Use and reuse pre-allocated PendingRequest objects = less memory
  1319. // churning.
  1320. var i = this.pendingRingBuffer.length;
  1321. while ( i-- ) {
  1322. this.pendingRingBuffer[i] = new this.PendingRequest();
  1323. }
  1324. },
  1325. createPendingRequest: function(url) {
  1326. var bucket;
  1327. var i = this.pendingWritePointer;
  1328. this.pendingWritePointer = i + 1 & 31;
  1329. var preq = this.pendingRingBuffer[i];
  1330. // Cleanup unserviced pending request
  1331. if ( preq._key !== '' ) {
  1332. bucket = this.pendingURLToIndex.get(preq._key);
  1333. if ( Array.isArray(bucket) ) {
  1334. // Assuming i in array
  1335. var pos = bucket.indexOf(i);
  1336. bucket.splice(pos, 1);
  1337. if ( bucket.length === 1 ) {
  1338. this.pendingURLToIndex.set(preq._key, bucket[0]);
  1339. }
  1340. } else if ( typeof bucket === 'number' ) {
  1341. // Assuming bucket === i
  1342. this.pendingURLToIndex.delete(preq._key);
  1343. }
  1344. }
  1345. // Would be much simpler if a url could not appear more than once.
  1346. bucket = this.pendingURLToIndex.get(url);
  1347. if ( bucket === undefined ) {
  1348. this.pendingURLToIndex.set(url, i);
  1349. } else if ( Array.isArray(bucket) ) {
  1350. bucket = bucket.push(i);
  1351. } else {
  1352. bucket = [bucket, i];
  1353. }
  1354. preq._key = url;
  1355. return preq;
  1356. },
  1357. lookupPendingRequest: function(url) {
  1358. var i = this.pendingURLToIndex.get(url);
  1359. if ( i === undefined ) {
  1360. return null;
  1361. }
  1362. if ( Array.isArray(i) ) {
  1363. var bucket = i;
  1364. i = bucket.shift();
  1365. if ( bucket.length === 1 ) {
  1366. this.pendingURLToIndex.set(url, bucket[0]);
  1367. }
  1368. } else {
  1369. this.pendingURLToIndex.delete(url);
  1370. }
  1371. var preq = this.pendingRingBuffer[i];
  1372. preq._key = ''; // mark as "serviced"
  1373. return preq;
  1374. },
  1375. handleRequest: function(channel, URI, tabId, rawType) {
  1376. var type = this.typeMap[rawType] || 'other';
  1377. var onBeforeRequest = vAPI.net.onBeforeRequest;
  1378. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  1379. return false;
  1380. }
  1381. var result = onBeforeRequest.callback({
  1382. hostname: URI.asciiHost,
  1383. parentFrameId: type === 'main_frame' ? -1 : 0,
  1384. tabId: tabId,
  1385. type: type,
  1386. url: URI.asciiSpec
  1387. });
  1388. if ( typeof result !== 'object' ) {
  1389. return false;
  1390. }
  1391. channel.cancel(this.ABORT);
  1392. return true;
  1393. },
  1394. handleRequestHeaders: function(channel, URI, tabId, rawType) {
  1395. var type = this.typeMap[rawType] || 'other';
  1396. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  1397. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  1398. return;
  1399. }
  1400. var requestHeaders = httpRequestHeadersFactory(channel);
  1401. onBeforeSendHeaders.callback({
  1402. hostname: URI.asciiHost,
  1403. parentFrameId: type === 'main_frame' ? -1 : 0,
  1404. requestHeaders: requestHeaders,
  1405. tabId: tabId,
  1406. type: type,
  1407. url: URI.asciiSpec
  1408. });
  1409. requestHeaders.dispose();
  1410. },
  1411. channelDataFromChannel: function(channel) {
  1412. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1413. try {
  1414. return channel.getProperty(this.REQDATAKEY);
  1415. } catch (ex) {
  1416. }
  1417. }
  1418. return null;
  1419. },
  1420. // https://github.com/gorhill/uMatrix/issues/165
  1421. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  1422. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  1423. // care about embedded frames topography.
  1424. // Also:
  1425. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  1426. tabIdFromChannel: function(channel) {
  1427. var aWindow;
  1428. if ( channel.notificationCallbacks ) {
  1429. try {
  1430. var loadContext = channel
  1431. .notificationCallbacks
  1432. .getInterface(Ci.nsILoadContext);
  1433. if ( loadContext.topFrameElement ) {
  1434. return tabWatcher.tabIdFromTarget(loadContext.topFrameElement);
  1435. }
  1436. aWindow = loadContext.associatedWindow;
  1437. } catch (ex) {
  1438. //console.error(ex);
  1439. }
  1440. }
  1441. try {
  1442. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  1443. aWindow = channel
  1444. .loadGroup
  1445. .notificationCallbacks
  1446. .getInterface(Ci.nsILoadContext)
  1447. .associatedWindow;
  1448. }
  1449. if ( aWindow ) {
  1450. return tabWatcher.tabIdFromTarget(
  1451. aWindow
  1452. .getInterface(Ci.nsIWebNavigation)
  1453. .QueryInterface(Ci.nsIDocShell)
  1454. .rootTreeItem
  1455. .QueryInterface(Ci.nsIInterfaceRequestor)
  1456. .getInterface(Ci.nsIDOMWindow)
  1457. .gBrowser
  1458. .getBrowserForContentWindow(aWindow)
  1459. );
  1460. }
  1461. } catch (ex) {
  1462. //console.error(ex);
  1463. }
  1464. return vAPI.noTabId;
  1465. },
  1466. rawtypeFromContentType: function(channel) {
  1467. var mime = channel.contentType;
  1468. if ( !mime ) {
  1469. return 0;
  1470. }
  1471. var pos = mime.indexOf('/');
  1472. if ( pos === -1 ) {
  1473. pos = mime.length;
  1474. }
  1475. return this.mimeTypeMap[mime.slice(0, pos)] || 0;
  1476. },
  1477. observe: function(channel, topic) {
  1478. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  1479. return;
  1480. }
  1481. var URI = channel.URI;
  1482. var channelData;
  1483. if (
  1484. topic === 'http-on-examine-response' ||
  1485. topic === 'http-on-examine-cached-response'
  1486. ) {
  1487. channelData = this.channelDataFromChannel(channel);
  1488. if ( channelData === null ) {
  1489. return;
  1490. }
  1491. var type = this.frameTypeMap[channelData[1]];
  1492. if ( !type ) {
  1493. return;
  1494. }
  1495. topic = 'Content-Security-Policy';
  1496. var result;
  1497. try {
  1498. result = channel.getResponseHeader(topic);
  1499. } catch (ex) {
  1500. result = null;
  1501. }
  1502. result = vAPI.net.onHeadersReceived.callback({
  1503. hostname: URI.asciiHost,
  1504. parentFrameId: type === 'main_frame' ? -1 : 0,
  1505. responseHeaders: result ? [{name: topic, value: result}] : [],
  1506. tabId: channelData[0],
  1507. type: type,
  1508. url: URI.asciiSpec
  1509. });
  1510. if ( result ) {
  1511. channel.setResponseHeader(
  1512. topic,
  1513. result.responseHeaders.pop().value,
  1514. true
  1515. );
  1516. }
  1517. return;
  1518. }
  1519. if ( topic === 'http-on-modify-request' ) {
  1520. channelData = this.channelDataFromChannel(channel);
  1521. if ( channelData === null ) {
  1522. return;
  1523. }
  1524. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1525. return;
  1526. }
  1527. // http-on-opening-request
  1528. var tabId, rawType;
  1529. var pendingRequest = this.lookupPendingRequest(URI.asciiSpec);
  1530. if ( pendingRequest !== null ) {
  1531. tabId = pendingRequest.tabId;
  1532. rawType = pendingRequest.rawType;
  1533. } else {
  1534. tabId = this.tabIdFromChannel(channel);
  1535. rawType = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1536. }
  1537. if ( this.handleRequest(channel, URI, tabId, rawType) ) {
  1538. return;
  1539. }
  1540. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1541. return;
  1542. }
  1543. // Carry data for behind-the-scene redirects
  1544. channel.setProperty(this.REQDATAKEY, [tabId, rawType]);
  1545. },
  1546. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1547. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1548. var result = this.ACCEPT;
  1549. // If error thrown, the redirect will fail
  1550. try {
  1551. var URI = newChannel.URI;
  1552. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1553. return;
  1554. }
  1555. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1556. return;
  1557. }
  1558. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1559. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1560. result = this.ABORT;
  1561. return;
  1562. }
  1563. // Carry the data on in case of multiple redirects
  1564. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1565. newChannel.setProperty(this.REQDATAKEY, channelData);
  1566. }
  1567. } catch (ex) {
  1568. // console.error(ex);
  1569. } finally {
  1570. callback.onRedirectVerifyCallback(result);
  1571. }
  1572. }
  1573. };
  1574. /******************************************************************************/
  1575. vAPI.net = {};
  1576. /******************************************************************************/
  1577. vAPI.net.registerListeners = function() {
  1578. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1579. new Set(this.onBeforeRequest.types) :
  1580. null;
  1581. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1582. new Set(this.onBeforeSendHeaders.types) :
  1583. null;
  1584. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1585. var shouldLoadListener = function(e) {
  1586. var details = e.data;
  1587. var pendingReq = httpObserver.createPendingRequest(details.url);
  1588. pendingReq.rawType = details.rawType;
  1589. pendingReq.tabId = tabWatcher.tabIdFromTarget(e.target);
  1590. };
  1591. vAPI.messaging.globalMessageManager.addMessageListener(
  1592. shouldLoadListenerMessageName,
  1593. shouldLoadListener
  1594. );
  1595. httpObserver.register();
  1596. cleanupTasks.push(function() {
  1597. vAPI.messaging.globalMessageManager.removeMessageListener(
  1598. shouldLoadListenerMessageName,
  1599. shouldLoadListener
  1600. );
  1601. httpObserver.unregister();
  1602. });
  1603. };
  1604. /******************************************************************************/
  1605. /******************************************************************************/
  1606. vAPI.toolbarButton = {
  1607. id: location.host + '-button',
  1608. type: 'view',
  1609. viewId: location.host + '-panel',
  1610. label: vAPI.app.name,
  1611. tooltiptext: vAPI.app.name,
  1612. tabs: {/*tabId: {badge: 0, img: boolean}*/},
  1613. init: null,
  1614. codePath: ''
  1615. };
  1616. /******************************************************************************/
  1617. // Non-Fennec: common code paths.
  1618. (function() {
  1619. if ( vAPI.fennec ) {
  1620. return;
  1621. }
  1622. var tbb = vAPI.toolbarButton;
  1623. tbb.onViewShowing = function({target}) {
  1624. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1625. };
  1626. tbb.onViewHiding = function({target}) {
  1627. target.parentNode.style.maxWidth = '';
  1628. target.firstChild.setAttribute('src', 'about:blank');
  1629. };
  1630. tbb.updateState = function(win, tabId) {
  1631. var button = win.document.getElementById(this.id);
  1632. if ( !button ) {
  1633. return;
  1634. }
  1635. var icon = this.tabs[tabId];
  1636. button.setAttribute('badge', icon && icon.badge || '');
  1637. button.classList.toggle('off', !icon || !icon.img);
  1638. var iconId = icon && icon.img ? icon.img : 'off';
  1639. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1640. button.style.listStyleImage = icon;
  1641. };
  1642. tbb.populatePanel = function(doc, panel) {
  1643. panel.setAttribute('id', this.viewId);
  1644. var iframe = doc.createElement('iframe');
  1645. iframe.setAttribute('type', 'content');
  1646. panel.appendChild(iframe);
  1647. var toPx = function(pixels) {
  1648. return pixels.toString() + 'px';
  1649. };
  1650. var scrollBarWidth = 0;
  1651. var resizeTimer = null;
  1652. var resizePopupDelayed = function(attempts) {
  1653. if ( resizeTimer !== null ) {
  1654. return;
  1655. }
  1656. // Sanity check
  1657. attempts = (attempts || 0) + 1;
  1658. if ( attempts > 1/*000*/ ) {
  1659. console.error('uMatrix> resizePopupDelayed: giving up after too many attempts');
  1660. return;
  1661. }
  1662. resizeTimer = vAPI.setTimeout(resizePopup, 10, attempts);
  1663. };
  1664. var resizePopup = function(attempts) {
  1665. resizeTimer = null;
  1666. var body = iframe.contentDocument.body;
  1667. panel.parentNode.style.maxWidth = 'none';
  1668. // We set a limit for height
  1669. var height = Math.min(body.clientHeight, 600);
  1670. // https://github.com/chrisaljoudi/uBlock/issues/730
  1671. // Voodoo programming: this recipe works
  1672. panel.style.setProperty('height', height + 'px');
  1673. iframe.style.setProperty('height', height + 'px');
  1674. // Adjust width for presence/absence of vertical scroll bar which may
  1675. // have appeared as a result of last operation.
  1676. var contentWindow = iframe.contentWindow;
  1677. var width = body.clientWidth;
  1678. if ( contentWindow.scrollMaxY !== 0 ) {
  1679. width += scrollBarWidth;
  1680. }
  1681. panel.style.setProperty('width', width + 'px');
  1682. // scrollMaxX should always be zero once we know the scrollbar width
  1683. if ( contentWindow.scrollMaxX !== 0 ) {
  1684. scrollBarWidth = contentWindow.scrollMaxX;
  1685. width += scrollBarWidth;
  1686. panel.style.setProperty('width', width + 'px');
  1687. }
  1688. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1689. resizePopupDelayed(attempts);
  1690. return;
  1691. }
  1692. };
  1693. var onPopupReady = function() {
  1694. var win = this.contentWindow;
  1695. if ( !win || win.location.host !== location.host ) {
  1696. return;
  1697. }
  1698. if ( typeof tbb.onBeforePopupReady === 'function' ) {
  1699. tbb.onBeforePopupReady.call(this);
  1700. }
  1701. new win.MutationObserver(resizePopupDelayed).observe(win.document.body, {
  1702. attributes: true,
  1703. characterData: true,
  1704. subtree: true
  1705. });
  1706. resizePopupDelayed();
  1707. };
  1708. iframe.addEventListener('load', onPopupReady, true);
  1709. };
  1710. })();
  1711. /******************************************************************************/
  1712. // Firefox 28 and less
  1713. (function() {
  1714. var tbb = vAPI.toolbarButton;
  1715. if ( tbb.init !== null ) {
  1716. return;
  1717. }
  1718. var CustomizableUI = null;
  1719. var forceLegacyToolbarButton = vAPI.localStorage.getBool('forceLegacyToolbarButton');
  1720. if ( !forceLegacyToolbarButton ) {
  1721. try {
  1722. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1723. } catch (ex) {
  1724. }
  1725. }
  1726. if ( CustomizableUI !== null ) {
  1727. return;
  1728. }
  1729. tbb.codePath = 'legacy';
  1730. tbb.id = 'umatrix-legacy-button'; // NOTE: must match legacy-toolbar-button.css
  1731. tbb.viewId = tbb.id + '-panel';
  1732. var sss = null;
  1733. var styleSheetUri = null;
  1734. var addLegacyToolbarButton = function(window) {
  1735. var document = window.document;
  1736. var toolbox = document.getElementById('navigator-toolbox') || document.getElementById('mail-toolbox');
  1737. if ( !toolbox ) {
  1738. return;
  1739. }
  1740. // palette might take a little longer to appear on some platforms,
  1741. // give it a small delay and try again.
  1742. var palette = toolbox.palette;
  1743. if ( !palette ) {
  1744. vAPI.setTimeout(function() {
  1745. if ( toolbox.palette ) {
  1746. addLegacyToolbarButton(window);
  1747. }
  1748. }, 250);
  1749. return;
  1750. }
  1751. var toolbarButton = document.createElement('toolbarbutton');
  1752. toolbarButton.setAttribute('id', tbb.id);
  1753. // type = panel would be more accurate, but doesn't look as good
  1754. toolbarButton.setAttribute('type', 'menu');
  1755. toolbarButton.setAttribute('removable', 'true');
  1756. toolbarButton.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional');
  1757. toolbarButton.setAttribute('label', tbb.label);
  1758. toolbarButton.setAttribute('tooltiptext', tbb.label);
  1759. var toolbarButtonPanel = document.createElement('panel');
  1760. // NOTE: Setting level to parent breaks the popup for PaleMoon under
  1761. // linux (mouse pointer misaligned with content). For some reason.
  1762. // toolbarButtonPanel.setAttribute('level', 'parent');
  1763. tbb.populatePanel(document, toolbarButtonPanel);
  1764. toolbarButtonPanel.addEventListener('popupshowing', tbb.onViewShowing);
  1765. toolbarButtonPanel.addEventListener('popuphiding', tbb.onViewHiding);
  1766. toolbarButton.appendChild(toolbarButtonPanel);
  1767. palette.appendChild(toolbarButton);
  1768. tbb.closePopup = function() {
  1769. toolbarButtonPanel.hidePopup();
  1770. };
  1771. // No button yet so give it a default location. If forcing the button,
  1772. // just put in in the palette rather than on any specific toolbar (who
  1773. // knows what toolbars will be available or visible!)
  1774. var toolbar;
  1775. if ( !vAPI.localStorage.getBool('legacyToolbarButtonAdded') ) {
  1776. vAPI.localStorage.setBool('legacyToolbarButtonAdded', 'true');
  1777. toolbar = document.getElementById('nav-bar');
  1778. if ( toolbar === null ) {
  1779. return;
  1780. }
  1781. // https://github.com/gorhill/uBlock/issues/264
  1782. // Find a child customizable palette, if any.
  1783. toolbar = toolbar.querySelector('.customization-target') || toolbar;
  1784. toolbar.appendChild(toolbarButton);
  1785. toolbar.setAttribute('currentset', toolbar.currentSet);
  1786. document.persist(toolbar.id, 'currentset');
  1787. return;
  1788. }
  1789. // Find the place to put the button
  1790. var toolbars = toolbox.externalToolbars.slice();
  1791. for ( var child of toolbox.children ) {
  1792. if ( child.localName === 'toolbar' ) {
  1793. toolbars.push(child);
  1794. }
  1795. }
  1796. for ( toolbar of toolbars ) {
  1797. var currentsetString = toolbar.getAttribute('currentset');
  1798. if ( !currentsetString ) {
  1799. continue;
  1800. }
  1801. var currentset = currentsetString.split(',');
  1802. var index = currentset.indexOf(tbb.id);
  1803. if ( index === -1 ) {
  1804. continue;
  1805. }
  1806. // Found our button on this toolbar - but where on it?
  1807. var before = null;
  1808. for ( var i = index + 1; i < currentset.length; i++ ) {
  1809. before = document.getElementById(currentset[i]);
  1810. if ( before === null ) {
  1811. continue;
  1812. }
  1813. toolbar.insertItem(tbb.id, before);
  1814. break;
  1815. }
  1816. if ( before === null ) {
  1817. toolbar.insertItem(tbb.id);
  1818. }
  1819. }
  1820. };
  1821. var onPopupCloseRequested = function({target}) {
  1822. if ( typeof tbb.closePopup === 'function' ) {
  1823. tbb.closePopup(target);
  1824. }
  1825. };
  1826. var shutdown = function() {
  1827. for ( var win of vAPI.tabs.getWindows() ) {
  1828. var toolbarButton = win.document.getElementById(tbb.id);
  1829. if ( toolbarButton ) {
  1830. toolbarButton.parentNode.removeChild(toolbarButton);
  1831. }
  1832. }
  1833. if ( sss === null ) {
  1834. return;
  1835. }
  1836. if ( sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  1837. sss.unregisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  1838. }
  1839. sss = null;
  1840. styleSheetUri = null;
  1841. vAPI.messaging.globalMessageManager.removeMessageListener(
  1842. location.host + ':closePopup',
  1843. onPopupCloseRequested
  1844. );
  1845. };
  1846. tbb.attachToNewWindow = function(win) {
  1847. addLegacyToolbarButton(win);
  1848. };
  1849. tbb.init = function() {
  1850. vAPI.messaging.globalMessageManager.addMessageListener(
  1851. location.host + ':closePopup',
  1852. onPopupCloseRequested
  1853. );
  1854. sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);
  1855. styleSheetUri = Services.io.newURI(vAPI.getURL("css/legacy-toolbar-button.css"), null, null);
  1856. // Register global so it works in all windows, including palette
  1857. if ( !sss.sheetRegistered(styleSheetUri, sss.AUTHOR_SHEET) ) {
  1858. sss.loadAndRegisterSheet(styleSheetUri, sss.AUTHOR_SHEET);
  1859. }
  1860. cleanupTasks.push(shutdown);
  1861. };
  1862. })();
  1863. /******************************************************************************/
  1864. // Firefox Australis < 36.
  1865. (function() {
  1866. var tbb = vAPI.toolbarButton;
  1867. if ( tbb.init !== null ) {
  1868. return;
  1869. }
  1870. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') >= 0 ) {
  1871. return null;
  1872. }
  1873. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  1874. return null;
  1875. }
  1876. var CustomizableUI = null;
  1877. try {
  1878. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1879. } catch (ex) {
  1880. }
  1881. if ( CustomizableUI === null ) {
  1882. return;
  1883. }
  1884. tbb.codePath = 'australis';
  1885. tbb.CustomizableUI = CustomizableUI;
  1886. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  1887. var styleURI = null;
  1888. var onPopupCloseRequested = function({target}) {
  1889. if ( typeof tbb.closePopup === 'function' ) {
  1890. tbb.closePopup(target);
  1891. }
  1892. };
  1893. var shutdown = function() {
  1894. CustomizableUI.destroyWidget(tbb.id);
  1895. for ( var win of vAPI.tabs.getWindows() ) {
  1896. var panel = win.document.getElementById(tbb.viewId);
  1897. panel.parentNode.removeChild(panel);
  1898. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1899. .getInterface(Ci.nsIDOMWindowUtils)
  1900. .removeSheet(styleURI, 1);
  1901. }
  1902. vAPI.messaging.globalMessageManager.removeMessageListener(
  1903. location.host + ':closePopup',
  1904. onPopupCloseRequested
  1905. );
  1906. };
  1907. tbb.onBeforeCreated = function(doc) {
  1908. var panel = doc.createElement('panelview');
  1909. this.populatePanel(doc, panel);
  1910. doc.getElementById('PanelUI-multiView').appendChild(panel);
  1911. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1912. .getInterface(Ci.nsIDOMWindowUtils)
  1913. .loadSheet(styleURI, 1);
  1914. };
  1915. tbb.onBeforePopupReady = function() {
  1916. // https://github.com/gorhill/uBlock/issues/83
  1917. // Add `portrait` class if width is constrained.
  1918. try {
  1919. this.contentDocument.body.classList.toggle(
  1920. 'portrait',
  1921. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  1922. );
  1923. } catch (ex) {
  1924. /* noop */
  1925. }
  1926. };
  1927. tbb.init = function() {
  1928. vAPI.messaging.globalMessageManager.addMessageListener(
  1929. location.host + ':closePopup',
  1930. onPopupCloseRequested
  1931. );
  1932. var style = [
  1933. '#' + this.id + '.off {',
  1934. 'list-style-image: url(',
  1935. vAPI.getURL('img/browsericons/icon19-off.png'),
  1936. ');',
  1937. '}',
  1938. '#' + this.id + ' {',
  1939. 'list-style-image: url(',
  1940. vAPI.getURL('img/browsericons/icon19.png'),
  1941. ');',
  1942. '}',
  1943. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1944. 'width: 160px;',
  1945. 'height: 290px;',
  1946. 'overflow: hidden !important;',
  1947. '}',
  1948. '#' + this.id + '[badge]:not([badge=""])::after {',
  1949. 'position: absolute;',
  1950. 'margin-left: -16px;',
  1951. 'margin-top: 3px;',
  1952. 'padding: 1px 2px;',
  1953. 'font-size: 9px;',
  1954. 'font-weight: bold;',
  1955. 'color: #fff;',
  1956. 'background: #000;',
  1957. 'content: attr(badge);',
  1958. '}'
  1959. ];
  1960. styleURI = Services.io.newURI(
  1961. 'data:text/css,' + encodeURIComponent(style.join('')),
  1962. null,
  1963. null
  1964. );
  1965. this.closePopup = function(tabBrowser) {
  1966. CustomizableUI.hidePanelForNode(
  1967. tabBrowser.ownerDocument.getElementById(this.viewId)
  1968. );
  1969. };
  1970. CustomizableUI.createWidget(this);
  1971. cleanupTasks.push(shutdown);
  1972. };
  1973. })();
  1974. /******************************************************************************/
  1975. // Firefox Australis >= 36.
  1976. (function() {
  1977. var tbb = vAPI.toolbarButton;
  1978. if ( tbb.init !== null ) {
  1979. return;
  1980. }
  1981. if ( Services.vc.compare(Services.appinfo.platformVersion, '36.0') < 0 ) {
  1982. return null;
  1983. }
  1984. if ( vAPI.localStorage.getBool('forceLegacyToolbarButton') ) {
  1985. return null;
  1986. }
  1987. var CustomizableUI = null;
  1988. try {
  1989. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1990. } catch (ex) {
  1991. }
  1992. if ( CustomizableUI === null ) {
  1993. return null;
  1994. }
  1995. tbb.codePath = 'australis';
  1996. tbb.CustomizableUI = CustomizableUI;
  1997. tbb.defaultArea = CustomizableUI.AREA_NAVBAR;
  1998. var CUIEvents = {};
  1999. var badgeCSSRules = [
  2000. 'background: #000',
  2001. 'color: #fff'
  2002. ].join(';');
  2003. var updateBadgeStyle = function() {
  2004. for ( var win of vAPI.tabs.getWindows() ) {
  2005. var button = win.document.getElementById(tbb.id);
  2006. if ( button === null ) {
  2007. continue;
  2008. }
  2009. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  2010. button,
  2011. 'class',
  2012. 'toolbarbutton-badge'
  2013. );
  2014. if ( !badge ) {
  2015. continue;
  2016. }
  2017. badge.style.cssText = badgeCSSRules;
  2018. }
  2019. };
  2020. var updateBadge = function() {
  2021. var wId = tbb.id;
  2022. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  2023. for ( var win of vAPI.tabs.getWindows() ) {
  2024. var button = win.document.getElementById(wId);
  2025. if ( button === null ) {
  2026. continue;
  2027. }
  2028. if ( buttonInPanel ) {
  2029. button.classList.remove('badged-button');
  2030. continue;
  2031. }
  2032. button.classList.add('badged-button');
  2033. }
  2034. if ( buttonInPanel ) {
  2035. return;
  2036. }
  2037. // Anonymous elements need some time to be reachable
  2038. vAPI.setTimeout(updateBadgeStyle, 250);
  2039. }.bind(CUIEvents);
  2040. // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/CustomizableUI.jsm#Listeners
  2041. CUIEvents.onCustomizeEnd = updateBadge;
  2042. CUIEvents.onWidgetAdded = updateBadge;
  2043. CUIEvents.onWidgetUnderflow = updateBadge;
  2044. var onPopupCloseRequested = function({target}) {
  2045. if ( typeof tbb.closePopup === 'function' ) {
  2046. tbb.closePopup(target);
  2047. }
  2048. };
  2049. var shutdown = function() {
  2050. CustomizableUI.removeListener(CUIEvents);
  2051. CustomizableUI.destroyWidget(tbb.id);
  2052. for ( var win of vAPI.tabs.getWindows() ) {
  2053. var panel = win.document.getElementById(tbb.viewId);
  2054. panel.parentNode.removeChild(panel);
  2055. win.QueryInterface(Ci.nsIInterfaceRequestor)
  2056. .getInterface(Ci.nsIDOMWindowUtils)
  2057. .removeSheet(styleURI, 1);
  2058. }
  2059. vAPI.messaging.globalMessageManager.removeMessageListener(
  2060. location.host + ':closePopup',
  2061. onPopupCloseRequested
  2062. );
  2063. };
  2064. var styleURI = null;
  2065. tbb.onBeforeCreated = function(doc) {
  2066. var panel = doc.createElement('panelview');
  2067. this.populatePanel(doc, panel);
  2068. doc.getElementById('PanelUI-multiView').appendChild(panel);
  2069. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  2070. .getInterface(Ci.nsIDOMWindowUtils)
  2071. .loadSheet(styleURI, 1);
  2072. };
  2073. tbb.onCreated = function(button) {
  2074. button.setAttribute('badge', '');
  2075. vAPI.setTimeout(updateBadge, 250);
  2076. };
  2077. tbb.onBeforePopupReady = function() {
  2078. // https://github.com/gorhill/uBlock/issues/83
  2079. // Add `portrait` class if width is constrained.
  2080. try {
  2081. this.contentDocument.body.classList.toggle(
  2082. 'portrait',
  2083. CustomizableUI.getWidget(tbb.id).areaType === CustomizableUI.TYPE_MENU_PANEL
  2084. );
  2085. } catch (ex) {
  2086. /* noop */
  2087. }
  2088. };
  2089. tbb.closePopup = function(tabBrowser) {
  2090. CustomizableUI.hidePanelForNode(
  2091. tabBrowser.ownerDocument.getElementById(tbb.viewId)
  2092. );
  2093. };
  2094. tbb.init = function() {
  2095. vAPI.messaging.globalMessageManager.addMessageListener(
  2096. location.host + ':closePopup',
  2097. onPopupCloseRequested
  2098. );
  2099. CustomizableUI.addListener(CUIEvents);
  2100. var style = [
  2101. '#' + this.id + '.off {',
  2102. 'list-style-image: url(',
  2103. vAPI.getURL('img/browsericons/icon19-off.png'),
  2104. ');',
  2105. '}',
  2106. '#' + this.id + ' {',
  2107. 'list-style-image: url(',
  2108. vAPI.getURL('img/browsericons/icon19-19.png'),
  2109. ');',
  2110. '}',
  2111. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  2112. 'width: 160px;',
  2113. 'height: 290px;',
  2114. 'overflow: hidden !important;',
  2115. '}'
  2116. ];
  2117. styleURI = Services.io.newURI(
  2118. 'data:text/css,' + encodeURIComponent(style.join('')),
  2119. null,
  2120. null
  2121. );
  2122. CustomizableUI.createWidget(this);
  2123. cleanupTasks.push(shutdown);
  2124. };
  2125. })();
  2126. /******************************************************************************/
  2127. // No toolbar button.
  2128. (function() {
  2129. // Just to ensure the number of cleanup tasks is as expected: toolbar
  2130. // button code is one single cleanup task regardless of platform.
  2131. if ( vAPI.toolbarButton.init === null ) {
  2132. cleanupTasks.push(function(){});
  2133. }
  2134. })();
  2135. /******************************************************************************/
  2136. if ( vAPI.toolbarButton.init !== null ) {
  2137. vAPI.toolbarButton.init();
  2138. }
  2139. /******************************************************************************/
  2140. /******************************************************************************/
  2141. vAPI.contextMenu = {
  2142. contextMap: {
  2143. frame: 'inFrame',
  2144. link: 'onLink',
  2145. image: 'onImage',
  2146. audio: 'onAudio',
  2147. video: 'onVideo',
  2148. editable: 'onEditableArea'
  2149. }
  2150. };
  2151. /******************************************************************************/
  2152. vAPI.contextMenu.displayMenuItem = function({target}) {
  2153. var doc = target.ownerDocument;
  2154. var gContextMenu = doc.defaultView.gContextMenu;
  2155. if ( !gContextMenu.browser ) {
  2156. return;
  2157. }
  2158. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  2159. var currentURI = gContextMenu.browser.currentURI;
  2160. // https://github.com/chrisaljoudi/uBlock/issues/105
  2161. // TODO: Should the element picker works on any kind of pages?
  2162. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  2163. menuitem.hidden = true;
  2164. return;
  2165. }
  2166. var ctx = vAPI.contextMenu.contexts;
  2167. if ( !ctx ) {
  2168. menuitem.hidden = false;
  2169. return;
  2170. }
  2171. var ctxMap = vAPI.contextMenu.contextMap;
  2172. for ( var context of ctx ) {
  2173. if (
  2174. context === 'page' &&
  2175. !gContextMenu.onLink &&
  2176. !gContextMenu.onImage &&
  2177. !gContextMenu.onEditableArea &&
  2178. !gContextMenu.inFrame &&
  2179. !gContextMenu.onVideo &&
  2180. !gContextMenu.onAudio
  2181. ) {
  2182. menuitem.hidden = false;
  2183. return;
  2184. }
  2185. if ( gContextMenu[ctxMap[context]] ) {
  2186. menuitem.hidden = false;
  2187. return;
  2188. }
  2189. }
  2190. menuitem.hidden = true;
  2191. };
  2192. /******************************************************************************/
  2193. vAPI.contextMenu.register = function(doc) {
  2194. if ( !this.menuItemId ) {
  2195. return;
  2196. }
  2197. var contextMenu = doc.getElementById('contentAreaContextMenu');
  2198. var menuitem = doc.createElement('menuitem');
  2199. menuitem.setAttribute('id', this.menuItemId);
  2200. menuitem.setAttribute('label', this.menuLabel);
  2201. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  2202. menuitem.setAttribute('class', 'menuitem-iconic');
  2203. menuitem.addEventListener('command', this.onCommand);
  2204. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  2205. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  2206. };
  2207. /******************************************************************************/
  2208. vAPI.contextMenu.unregister = function(doc) {
  2209. if ( !this.menuItemId ) {
  2210. return;
  2211. }
  2212. var menuitem = doc.getElementById(this.menuItemId);
  2213. if ( menuitem === null ) {
  2214. return;
  2215. }
  2216. var contextMenu = menuitem.parentNode;
  2217. menuitem.removeEventListener('command', this.onCommand);
  2218. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  2219. contextMenu.removeChild(menuitem);
  2220. };
  2221. /******************************************************************************/
  2222. vAPI.contextMenu.create = function(details, callback) {
  2223. this.menuItemId = details.id;
  2224. this.menuLabel = details.title;
  2225. this.contexts = details.contexts;
  2226. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  2227. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  2228. } else {
  2229. // default in Chrome
  2230. this.contexts = ['page'];
  2231. }
  2232. this.onCommand = function() {
  2233. var gContextMenu = getOwnerWindow(this).gContextMenu;
  2234. var details = {
  2235. menuItemId: this.id
  2236. };
  2237. if ( gContextMenu.inFrame ) {
  2238. details.tagName = 'iframe';
  2239. // Probably won't work with e10s
  2240. details.frameUrl = gContextMenu.focusedWindow.location.href;
  2241. } else if ( gContextMenu.onImage ) {
  2242. details.tagName = 'img';
  2243. details.srcUrl = gContextMenu.mediaURL;
  2244. } else if ( gContextMenu.onAudio ) {
  2245. details.tagName = 'audio';
  2246. details.srcUrl = gContextMenu.mediaURL;
  2247. } else if ( gContextMenu.onVideo ) {
  2248. details.tagName = 'video';
  2249. details.srcUrl = gContextMenu.mediaURL;
  2250. } else if ( gContextMenu.onLink ) {
  2251. details.tagName = 'a';
  2252. details.linkUrl = gContextMenu.linkURL;
  2253. }
  2254. callback(details, {
  2255. id: tabWatcher.tabIdFromTarget(gContextMenu.browser),
  2256. url: gContextMenu.browser.currentURI.asciiSpec
  2257. });
  2258. };
  2259. for ( var win of vAPI.tabs.getWindows() ) {
  2260. this.register(win.document);
  2261. }
  2262. };
  2263. /******************************************************************************/
  2264. vAPI.contextMenu.remove = function() {
  2265. for ( var win of vAPI.tabs.getWindows() ) {
  2266. this.unregister(win.document);
  2267. }
  2268. this.menuItemId = null;
  2269. this.menuLabel = null;
  2270. this.contexts = null;
  2271. this.onCommand = null;
  2272. };
  2273. /******************************************************************************/
  2274. /******************************************************************************/
  2275. var optionsObserver = {
  2276. addonId: 'uMatrix@raymondhill.net',
  2277. register: function() {
  2278. Services.obs.addObserver(this, 'addon-options-displayed', false);
  2279. cleanupTasks.push(this.unregister.bind(this));
  2280. var browser = tabWatcher.currentBrowser();
  2281. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  2282. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  2283. }
  2284. },
  2285. unregister: function() {
  2286. Services.obs.removeObserver(this, 'addon-options-displayed');
  2287. },
  2288. setupOptionsButton: function(doc, id, page) {
  2289. var button = doc.getElementById(id);
  2290. if ( button === null ) {
  2291. return;
  2292. }
  2293. button.addEventListener('command', function() {
  2294. vAPI.tabs.open({ url: page, index: -1 });
  2295. });
  2296. button.label = vAPI.i18n(id);
  2297. },
  2298. observe: function(doc, topic, addonId) {
  2299. if ( addonId !== this.addonId ) {
  2300. return;
  2301. }
  2302. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  2303. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  2304. }
  2305. };
  2306. optionsObserver.register();
  2307. /******************************************************************************/
  2308. /******************************************************************************/
  2309. vAPI.lastError = function() {
  2310. return null;
  2311. };
  2312. /******************************************************************************/
  2313. /******************************************************************************/
  2314. // This is called only once, when everything has been loaded in memory after
  2315. // the extension was launched. It can be used to inject content scripts
  2316. // in already opened web pages, to remove whatever nuisance could make it to
  2317. // the web pages before uBlock was ready.
  2318. vAPI.onLoadAllCompleted = function() {
  2319. for ( var browser of tabWatcher.browsers() ) {
  2320. browser.messageManager.sendAsyncMessage(
  2321. location.host + '-load-completed'
  2322. );
  2323. }
  2324. };
  2325. /******************************************************************************/
  2326. /******************************************************************************/
  2327. // Likelihood is that we do not have to punycode: given punycode overhead,
  2328. // it's faster to check and skip than do it unconditionally all the time.
  2329. var punycodeHostname = punycode.toASCII;
  2330. var isNotASCII = /[^\x21-\x7F]/;
  2331. vAPI.punycodeHostname = function(hostname) {
  2332. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  2333. };
  2334. vAPI.punycodeURL = function(url) {
  2335. if ( isNotASCII.test(url) ) {
  2336. return Services.io.newURI(url, null, null).asciiSpec;
  2337. }
  2338. return url;
  2339. };
  2340. /******************************************************************************/
  2341. /******************************************************************************/
  2342. vAPI.browserData = {};
  2343. /******************************************************************************/
  2344. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  2345. vAPI.browserData.clearCache = function(callback) {
  2346. // PURGE_DISK_DATA_ONLY:1
  2347. // PURGE_DISK_ALL:2
  2348. // PURGE_EVERYTHING:3
  2349. // However I verified that not argument does clear the cache data.
  2350. Services.cache2.clear();
  2351. if ( typeof callback === 'function' ) {
  2352. callback();
  2353. }
  2354. };
  2355. /******************************************************************************/
  2356. vAPI.browserData.clearOrigin = function(/* domain */) {
  2357. // TODO
  2358. };
  2359. /******************************************************************************/
  2360. /******************************************************************************/
  2361. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  2362. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  2363. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  2364. vAPI.cookies = {};
  2365. /******************************************************************************/
  2366. vAPI.cookies.CookieEntry = function(ffCookie) {
  2367. this.domain = ffCookie.host;
  2368. this.name = ffCookie.name;
  2369. this.path = ffCookie.path;
  2370. this.secure = ffCookie.isSecure === true;
  2371. this.session = ffCookie.expires === 0;
  2372. this.value = ffCookie.value;
  2373. };
  2374. /******************************************************************************/
  2375. vAPI.cookies.start = function() {
  2376. Services.obs.addObserver(this, 'cookie-changed', false);
  2377. Services.obs.addObserver(this, 'private-cookie-changed', false);
  2378. cleanupTasks.push(this.stop.bind(this));
  2379. };
  2380. /******************************************************************************/
  2381. vAPI.cookies.stop = function() {
  2382. Services.obs.removeObserver(this, 'cookie-changed');
  2383. Services.obs.removeObserver(this, 'private-cookie-changed');
  2384. };
  2385. /******************************************************************************/
  2386. vAPI.cookies.observe = function(subject, topic, reason) {
  2387. //if ( topic !== 'cookie-changed' && topic !== 'private-cookie-changed' ) {
  2388. // return;
  2389. //}
  2390. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  2391. return;
  2392. }
  2393. if ( typeof this.onChanged === 'function' ) {
  2394. this.onChanged(new this.CookieEntry(subject));
  2395. }
  2396. };
  2397. /******************************************************************************/
  2398. // Meant and expected to be asynchronous.
  2399. vAPI.cookies.getAll = function(callback) {
  2400. if ( typeof callback !== 'function' ) {
  2401. return;
  2402. }
  2403. var onAsync = function() {
  2404. var out = [];
  2405. var enumerator = Services.cookies.enumerator;
  2406. var ffcookie;
  2407. while ( enumerator.hasMoreElements() ) {
  2408. ffcookie = enumerator.getNext();
  2409. if ( ffcookie instanceof Ci.nsICookie ) {
  2410. out.push(new this.CookieEntry(ffcookie));
  2411. }
  2412. }
  2413. callback(out);
  2414. };
  2415. vAPI.setTimeout(onAsync.bind(this), 0);
  2416. };
  2417. /******************************************************************************/
  2418. vAPI.cookies.remove = function(details, callback) {
  2419. var uri = Services.io.newURI(details.url, null, null);
  2420. var cookies = Services.cookies;
  2421. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  2422. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  2423. if ( typeof callback === 'function' ) {
  2424. callback({
  2425. domain: uri.asciiHost,
  2426. name: details.name,
  2427. path: uri.path
  2428. });
  2429. }
  2430. };
  2431. /******************************************************************************/
  2432. /******************************************************************************/
  2433. })();
  2434. /******************************************************************************/