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.

2799 lines
85 KiB

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