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.

1992 lines
59 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
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
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
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
  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. // List of things that needs to be destroyed when disabling the extension
  53. // Only functions should be added to it
  54. var cleanupTasks = [];
  55. // This must be updated manually, every time a new task is added/removed
  56. // Fixed by github.com/AlexVallat:
  57. // https://github.com/AlexVallat/uBlock/commit/7b781248f00cbe3d61b1cc367c440db80fa06049
  58. // 7 instances of cleanupTasks.push, but one is unique to fennec, and one to desktop.
  59. var expectedNumberOfCleanups = 7;
  60. window.addEventListener('unload', function() {
  61. for ( var cleanup of cleanupTasks ) {
  62. cleanup();
  63. }
  64. if ( cleanupTasks.length < expectedNumberOfCleanups ) {
  65. console.error(
  66. 'uMatrix> Cleanup tasks performed: %s (out of %s)',
  67. cleanupTasks.length,
  68. expectedNumberOfCleanups
  69. );
  70. }
  71. // frameModule needs to be cleared too
  72. var frameModule = {};
  73. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  74. frameModule.contentObserver.unregister();
  75. Cu.unload(vAPI.getURL('frameModule.js'));
  76. });
  77. /******************************************************************************/
  78. var SQLite = {
  79. db: null,
  80. open: function() {
  81. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  82. path.append('extension-data');
  83. if ( !path.exists() ) {
  84. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  85. }
  86. if ( !path.isDirectory() ) {
  87. throw Error('Should be a directory...');
  88. }
  89. path.append(location.host + '.sqlite');
  90. this.db = Services.storage.openDatabase(path);
  91. this.db.executeSimpleSQL(
  92. 'CREATE TABLE IF NOT EXISTS settings' +
  93. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  94. );
  95. cleanupTasks.push(function() {
  96. // VACUUM somewhere else, instead on unload?
  97. SQLite.run('VACUUM');
  98. SQLite.db.asyncClose();
  99. });
  100. },
  101. run: function(query, values, callback) {
  102. if ( !this.db ) {
  103. this.open();
  104. }
  105. var result = {};
  106. query = this.db.createAsyncStatement(query);
  107. if ( Array.isArray(values) && values.length ) {
  108. var i = values.length;
  109. while ( i-- ) {
  110. query.bindByIndex(i, values[i]);
  111. }
  112. }
  113. query.executeAsync({
  114. handleResult: function(rows) {
  115. if ( !rows || typeof callback !== 'function' ) {
  116. return;
  117. }
  118. var row;
  119. while ( row = rows.getNextRow() ) {
  120. // we assume that there will be two columns, since we're
  121. // using it only for preferences
  122. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  123. }
  124. },
  125. handleCompletion: function(reason) {
  126. if ( typeof callback === 'function' && reason === 0 ) {
  127. callback(result);
  128. }
  129. },
  130. handleError: function(error) {
  131. console.error('SQLite error ', error.result, error.message);
  132. }
  133. });
  134. }
  135. };
  136. /******************************************************************************/
  137. vAPI.storage = {
  138. QUOTA_BYTES: 100 * 1024 * 1024,
  139. sqlWhere: function(col, params) {
  140. if ( params > 0 ) {
  141. params = new Array(params + 1).join('?, ').slice(0, -2);
  142. return ' WHERE ' + col + ' IN (' + params + ')';
  143. }
  144. return '';
  145. },
  146. get: function(details, callback) {
  147. if ( typeof callback !== 'function' ) {
  148. return;
  149. }
  150. var values = [], defaults = false;
  151. if ( details !== null ) {
  152. if ( Array.isArray(details) ) {
  153. values = details;
  154. } else if ( typeof details === 'object' ) {
  155. defaults = true;
  156. values = Object.keys(details);
  157. } else {
  158. values = [details.toString()];
  159. }
  160. }
  161. SQLite.run(
  162. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  163. values,
  164. function(result) {
  165. var key;
  166. for ( key in result ) {
  167. result[key] = JSON.parse(result[key]);
  168. }
  169. if ( defaults ) {
  170. for ( key in details ) {
  171. if ( result[key] === undefined ) {
  172. result[key] = details[key];
  173. }
  174. }
  175. }
  176. callback(result);
  177. }
  178. );
  179. },
  180. set: function(details, callback) {
  181. var key, values = [], placeholders = [];
  182. for ( key in details ) {
  183. if ( !details.hasOwnProperty(key) ) {
  184. continue;
  185. }
  186. values.push(key);
  187. values.push(JSON.stringify(details[key]));
  188. placeholders.push('?, ?');
  189. }
  190. if ( !values.length ) {
  191. return;
  192. }
  193. SQLite.run(
  194. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  195. placeholders.join(' UNION SELECT '),
  196. values,
  197. callback
  198. );
  199. },
  200. remove: function(keys, callback) {
  201. if ( typeof keys === 'string' ) {
  202. keys = [keys];
  203. }
  204. SQLite.run(
  205. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  206. keys,
  207. callback
  208. );
  209. },
  210. clear: function(callback) {
  211. SQLite.run('DELETE FROM settings');
  212. SQLite.run('VACUUM', null, callback);
  213. },
  214. getBytesInUse: function(keys, callback) {
  215. if ( typeof callback !== 'function' ) {
  216. return;
  217. }
  218. SQLite.run(
  219. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  220. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  221. keys,
  222. function(result) {
  223. callback(result.size);
  224. }
  225. );
  226. }
  227. };
  228. /******************************************************************************/
  229. var windowWatcher = {
  230. onReady: function(e) {
  231. if ( e ) {
  232. this.removeEventListener(e.type, windowWatcher.onReady);
  233. }
  234. var wintype = this.document.documentElement.getAttribute('windowtype');
  235. if ( wintype !== 'navigator:browser' ) {
  236. return;
  237. }
  238. var tabContainer;
  239. var tabBrowser = getTabBrowser(this);
  240. if ( !tabBrowser ) {
  241. return;
  242. }
  243. if ( tabBrowser.tabContainer ) {
  244. // desktop Firefox
  245. tabContainer = tabBrowser.tabContainer;
  246. vAPI.contextMenu.register(this.document);
  247. } else {
  248. return;
  249. }
  250. tabContainer.addEventListener('TabClose', tabWatcher.onTabClose);
  251. tabContainer.addEventListener('TabSelect', tabWatcher.onTabSelect);
  252. // when new window is opened TabSelect doesn't run on the selected tab?
  253. },
  254. observe: function(win, topic) {
  255. if ( topic === 'domwindowopened' ) {
  256. win.addEventListener('DOMContentLoaded', this.onReady);
  257. }
  258. }
  259. };
  260. /******************************************************************************/
  261. var tabWatcher = {
  262. onTabClose: function({target}) {
  263. // target is tab in Firefox, browser in Fennec
  264. var tabId = vAPI.tabs.getTabId(target);
  265. vAPI.tabs.onClosed(tabId);
  266. delete vAPI.toolbarButton.tabs[tabId];
  267. },
  268. onTabSelect: function({target}) {
  269. vAPI.setIcon(vAPI.tabs.getTabId(target), getOwnerWindow(target));
  270. return;
  271. },
  272. };
  273. /******************************************************************************/
  274. vAPI.isBehindTheSceneTabId = function(tabId) {
  275. return tabId.toString() === '-1';
  276. };
  277. vAPI.noTabId = '-1';
  278. /******************************************************************************/
  279. var getTabBrowser = function(win) {
  280. return win.gBrowser || null;
  281. };
  282. /******************************************************************************/
  283. var getBrowserForTab = function(tab) {
  284. if ( !tab ) {
  285. return null;
  286. }
  287. return tab.linkedBrowser || null;
  288. };
  289. /******************************************************************************/
  290. var getOwnerWindow = function(target) {
  291. if ( target.ownerDocument ) {
  292. return target.ownerDocument.defaultView;
  293. }
  294. return null;
  295. };
  296. /******************************************************************************/
  297. vAPI.tabs = {};
  298. /******************************************************************************/
  299. vAPI.tabs.registerListeners = function() {
  300. // onClosed - handled in tabWatcher.onTabClose
  301. for ( var win of this.getWindows() ) {
  302. windowWatcher.onReady.call(win);
  303. }
  304. Services.ww.registerNotification(windowWatcher);
  305. cleanupTasks.push(function() {
  306. Services.ww.unregisterNotification(windowWatcher);
  307. for ( var win of vAPI.tabs.getWindows() ) {
  308. vAPI.contextMenu.unregister(win.document);
  309. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  310. var tabContainer;
  311. var tabBrowser = getTabBrowser(win);
  312. if ( !tabBrowser ) {
  313. continue;
  314. }
  315. if ( tabBrowser.tabContainer ) {
  316. tabContainer = tabBrowser.tabContainer;
  317. tabBrowser.removeTabsProgressListener(tabWatcher);
  318. }
  319. tabContainer.removeEventListener('TabClose', tabWatcher.onTabClose);
  320. tabContainer.removeEventListener('TabSelect', tabWatcher.onTabSelect);
  321. // Close extension tabs
  322. for ( var tab of tabBrowser.tabs ) {
  323. var browser = getBrowserForTab(tab);
  324. if ( browser === null ) {
  325. continue;
  326. }
  327. var URI = browser.currentURI;
  328. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  329. vAPI.tabs._remove(tab, getTabBrowser(win));
  330. }
  331. }
  332. }
  333. });
  334. };
  335. /******************************************************************************/
  336. vAPI.tabs.stack = new WeakMap();
  337. vAPI.tabs.stackId = 1;
  338. /******************************************************************************/
  339. vAPI.tabs.getTabId = function(target) {
  340. if ( !target ) {
  341. return vAPI.noTabId;
  342. }
  343. if ( target.linkedPanel ) {
  344. // target is a tab
  345. target = target.linkedBrowser;
  346. }
  347. if ( target.localName !== 'browser' ) {
  348. return vAPI.noTabId;
  349. }
  350. var tabId = this.stack.get(target);
  351. if ( !tabId ) {
  352. tabId = '' + this.stackId++;
  353. this.stack.set(target, tabId);
  354. }
  355. return tabId;
  356. };
  357. /******************************************************************************/
  358. // If tabIds is an array, then an array of tabs will be returned,
  359. // otherwise a single tab
  360. vAPI.tabs.getTabsForIds = function(tabIds) {
  361. var tabs = [];
  362. var singleTab = !Array.isArray(tabIds);
  363. if ( singleTab ) {
  364. tabIds = [tabIds];
  365. }
  366. for ( var tab of this.getAllSync() ) {
  367. var tabId = this.stack.get(getBrowserForTab(tab));
  368. if ( !tabId ) {
  369. continue;
  370. }
  371. if ( tabIds.indexOf(tabId) !== -1 ) {
  372. tabs.push(tab);
  373. }
  374. if ( tabs.length >= tabIds.length ) {
  375. break;
  376. }
  377. }
  378. return singleTab ? tabs[0] || null : tabs;
  379. };
  380. /******************************************************************************/
  381. vAPI.tabs.get = function(tabId, callback) {
  382. var tab, win;
  383. if ( tabId === null ) {
  384. win = Services.wm.getMostRecentWindow('navigator:browser');
  385. tab = getTabBrowser(win).selectedTab;
  386. tabId = this.getTabId(tab);
  387. } else {
  388. tab = this.getTabsForIds(tabId);
  389. if ( tab ) {
  390. win = getOwnerWindow(tab);
  391. }
  392. }
  393. // For internal use
  394. if ( typeof callback !== 'function' ) {
  395. return tab;
  396. }
  397. if ( !tab ) {
  398. callback();
  399. return;
  400. }
  401. var windows = this.getWindows();
  402. var browser = getBrowserForTab(tab);
  403. var tabBrowser = getTabBrowser(win);
  404. var tabIndex = tabBrowser.browsers.indexOf(browser);
  405. var tabTitle = tab.label;
  406. callback({
  407. id: tabId,
  408. index: tabIndex,
  409. windowId: windows.indexOf(win),
  410. active: tab === tabBrowser.selectedTab,
  411. url: browser.currentURI.asciiSpec,
  412. title: tabTitle
  413. });
  414. };
  415. /******************************************************************************/
  416. vAPI.tabs.getAllSync = function(window) {
  417. var win, tab;
  418. var tabs = [];
  419. for ( win of this.getWindows() ) {
  420. if ( window && window !== win ) {
  421. continue;
  422. }
  423. var tabBrowser = getTabBrowser(win);
  424. if ( tabBrowser === null ) {
  425. continue;
  426. }
  427. for ( tab of tabBrowser.tabs ) {
  428. tabs.push(tab);
  429. }
  430. }
  431. return tabs;
  432. };
  433. /******************************************************************************/
  434. vAPI.tabs.getAll = function(callback) {
  435. var tabs = [];
  436. var win, tab;
  437. for ( win of this.getWindows() ) {
  438. var tabBrowser = getTabBrowser(win);
  439. if ( tabBrowser === null ) {
  440. continue;
  441. }
  442. for ( tab of tabBrowser.tabs ) {
  443. tabs.push({
  444. id: this.getTabId(tab),
  445. url: getBrowserForTab(tab).currentURI.asciiSpec
  446. });
  447. }
  448. }
  449. callback(tabs);
  450. };
  451. /******************************************************************************/
  452. vAPI.tabs.getWindows = function() {
  453. var winumerator = Services.wm.getEnumerator('navigator:browser');
  454. var windows = [];
  455. while ( winumerator.hasMoreElements() ) {
  456. var win = winumerator.getNext();
  457. if ( !win.closed ) {
  458. windows.push(win);
  459. }
  460. }
  461. return windows;
  462. };
  463. /******************************************************************************/
  464. // properties of the details object:
  465. // url: 'URL', // the address that will be opened
  466. // tabId: 1, // the tab is used if set, instead of creating a new one
  467. // index: -1, // undefined: end of the list, -1: following tab, or after index
  468. // active: false, // opens the tab in background - true and undefined: foreground
  469. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  470. vAPI.tabs.open = function(details) {
  471. if ( !details.url ) {
  472. return null;
  473. }
  474. // extension pages
  475. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  476. details.url = vAPI.getURL(details.url);
  477. }
  478. var win, tab, tabBrowser;
  479. if ( details.select ) {
  480. var URI = Services.io.newURI(details.url, null, null);
  481. for ( tab of this.getAllSync() ) {
  482. var browser = getBrowserForTab(tab);
  483. // Or simply .equals if we care about the fragment
  484. if ( URI.equalsExceptRef(browser.currentURI) === false ) {
  485. continue;
  486. }
  487. this.select(tab);
  488. return;
  489. }
  490. }
  491. if ( details.active === undefined ) {
  492. details.active = true;
  493. }
  494. if ( details.tabId ) {
  495. tab = this.getTabsForIds(details.tabId);
  496. if ( tab ) {
  497. getBrowserForTab(tab).loadURI(details.url);
  498. return;
  499. }
  500. }
  501. win = Services.wm.getMostRecentWindow('navigator:browser');
  502. tabBrowser = getTabBrowser(win);
  503. if ( details.index === -1 ) {
  504. details.index = tabBrowser.browsers.indexOf(tabBrowser.selectedBrowser) + 1;
  505. }
  506. tab = tabBrowser.loadOneTab(details.url, {inBackground: !details.active});
  507. if ( details.index !== undefined ) {
  508. tabBrowser.moveTabTo(tab, details.index);
  509. }
  510. };
  511. /******************************************************************************/
  512. // Replace the URL of a tab. Noop if the tab does not exist.
  513. vAPI.tabs.replace = function(tabId, url) {
  514. var targetURL = url;
  515. // extension pages
  516. if ( /^[\w-]{2,}:/.test(targetURL) !== true ) {
  517. targetURL = vAPI.getURL(targetURL);
  518. }
  519. var tab = this.getTabsForIds(tabId);
  520. if ( tab ) {
  521. getBrowserForTab(tab).loadURI(targetURL);
  522. }
  523. };
  524. /******************************************************************************/
  525. vAPI.tabs._remove = function(tab, tabBrowser) {
  526. tabBrowser.removeTab(tab);
  527. };
  528. /******************************************************************************/
  529. vAPI.tabs.remove = function(tabIds) {
  530. if ( !Array.isArray(tabIds) ) {
  531. tabIds = [tabIds];
  532. }
  533. var tabs = this.getTabsForIds(tabIds);
  534. if ( tabs.length === 0 ) {
  535. return;
  536. }
  537. for ( var tab of tabs ) {
  538. this._remove(tab, getTabBrowser(getOwnerWindow(tab)));
  539. }
  540. };
  541. /******************************************************************************/
  542. vAPI.tabs.reload = function(tabId) {
  543. var tab = this.get(tabId);
  544. if ( !tab ) {
  545. return;
  546. }
  547. getBrowserForTab(tab).webNavigation.reload(
  548. Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE
  549. );
  550. };
  551. /******************************************************************************/
  552. vAPI.tabs.select = function(tab) {
  553. tab = typeof tab === 'object' ? tab : this.get(tab);
  554. if ( !tab ) {
  555. return;
  556. }
  557. getTabBrowser(getOwnerWindow(tab)).selectedTab = tab;
  558. };
  559. /******************************************************************************/
  560. vAPI.tabs.injectScript = function(tabId, details, callback) {
  561. var tab = this.get(tabId);
  562. if ( !tab ) {
  563. return;
  564. }
  565. if ( typeof details.file !== 'string' ) {
  566. return;
  567. }
  568. details.file = vAPI.getURL(details.file);
  569. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  570. location.host + ':broadcast',
  571. JSON.stringify({
  572. broadcast: true,
  573. channelName: 'vAPI',
  574. msg: {
  575. cmd: 'injectScript',
  576. details: details
  577. }
  578. })
  579. );
  580. if ( typeof callback === 'function' ) {
  581. vAPI.setTimeout(callback, 13);
  582. }
  583. };
  584. /******************************************************************************/
  585. vAPI.setIcon = function(tabId, iconId, badge) {
  586. // If badge is undefined, then setIcon was called from the TabSelect event
  587. var win;
  588. if ( badge === undefined ) {
  589. win = iconId;
  590. } else {
  591. win = Services.wm.getMostRecentWindow('navigator:browser');
  592. }
  593. var curTabId = vAPI.tabs.getTabId(getTabBrowser(win).selectedTab);
  594. var tb = vAPI.toolbarButton;
  595. // from 'TabSelect' event
  596. if ( tabId === undefined ) {
  597. tabId = curTabId;
  598. } else if ( badge !== undefined ) {
  599. tb.tabs[tabId] = { badge: badge, img: iconId };
  600. }
  601. if ( tabId === curTabId ) {
  602. tb.updateState(win, tabId);
  603. }
  604. };
  605. /******************************************************************************/
  606. vAPI.messaging = {
  607. get globalMessageManager() {
  608. return Cc['@mozilla.org/globalmessagemanager;1']
  609. .getService(Ci.nsIMessageListenerManager);
  610. },
  611. frameScript: vAPI.getURL('frameScript.js'),
  612. listeners: {},
  613. defaultHandler: null,
  614. NOOPFUNC: function(){},
  615. UNHANDLED: 'vAPI.messaging.notHandled'
  616. };
  617. /******************************************************************************/
  618. vAPI.messaging.listen = function(listenerName, callback) {
  619. this.listeners[listenerName] = callback;
  620. };
  621. /******************************************************************************/
  622. vAPI.messaging.onMessage = function({target, data}) {
  623. var messageManager = target.messageManager;
  624. if ( !messageManager ) {
  625. // Message came from a popup, and its message manager is not usable.
  626. // So instead we broadcast to the parent window.
  627. messageManager = getOwnerWindow(
  628. target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
  629. ).messageManager;
  630. }
  631. var channelNameRaw = data.channelName;
  632. var pos = channelNameRaw.indexOf('|');
  633. var channelName = channelNameRaw.slice(pos + 1);
  634. var callback = vAPI.messaging.NOOPFUNC;
  635. if ( data.requestId !== undefined ) {
  636. callback = CallbackWrapper.factory(
  637. messageManager,
  638. channelName,
  639. channelNameRaw.slice(0, pos),
  640. data.requestId
  641. ).callback;
  642. }
  643. var sender = {
  644. tab: {
  645. id: vAPI.tabs.getTabId(target)
  646. }
  647. };
  648. // Specific handler
  649. var r = vAPI.messaging.UNHANDLED;
  650. var listener = vAPI.messaging.listeners[channelName];
  651. if ( typeof listener === 'function' ) {
  652. r = listener(data.msg, sender, callback);
  653. }
  654. if ( r !== vAPI.messaging.UNHANDLED ) {
  655. return;
  656. }
  657. // Default handler
  658. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  659. if ( r !== vAPI.messaging.UNHANDLED ) {
  660. return;
  661. }
  662. console.error('uMatrix> messaging > unknown request: %o', data);
  663. // Unhandled:
  664. // Need to callback anyways in case caller expected an answer, or
  665. // else there is a memory leak on caller's side
  666. callback();
  667. };
  668. /******************************************************************************/
  669. vAPI.messaging.setup = function(defaultHandler) {
  670. // Already setup?
  671. if ( this.defaultHandler !== null ) {
  672. return;
  673. }
  674. if ( typeof defaultHandler !== 'function' ) {
  675. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  676. }
  677. this.defaultHandler = defaultHandler;
  678. this.globalMessageManager.addMessageListener(
  679. location.host + ':background',
  680. this.onMessage
  681. );
  682. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  683. cleanupTasks.push(function() {
  684. var gmm = vAPI.messaging.globalMessageManager;
  685. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  686. gmm.removeMessageListener(
  687. location.host + ':background',
  688. vAPI.messaging.onMessage
  689. );
  690. });
  691. };
  692. /******************************************************************************/
  693. vAPI.messaging.broadcast = function(message) {
  694. this.globalMessageManager.broadcastAsyncMessage(
  695. location.host + ':broadcast',
  696. JSON.stringify({broadcast: true, msg: message})
  697. );
  698. };
  699. /******************************************************************************/
  700. // This allows to avoid creating a closure for every single message which
  701. // expects an answer. Having a closure created each time a message is processed
  702. // has been always bothering me. Another benefit of the implementation here
  703. // is to reuse the callback proxy object, so less memory churning.
  704. //
  705. // https://developers.google.com/speed/articles/optimizing-javascript
  706. // "Creating a closure is significantly slower then creating an inner
  707. // function without a closure, and much slower than reusing a static
  708. // function"
  709. //
  710. // http://hacksoflife.blogspot.ca/2015/01/the-four-horsemen-of-performance.html
  711. // "the dreaded 'uniformly slow code' case where every function takes 1%
  712. // of CPU and you have to make one hundred separate performance optimizations
  713. // to improve performance at all"
  714. //
  715. // http://jsperf.com/closure-no-closure/2
  716. var CallbackWrapper = function(messageManager, channelName, listenerId, requestId) {
  717. this.callback = this.proxy.bind(this); // bind once
  718. this.init(messageManager, channelName, listenerId, requestId);
  719. };
  720. CallbackWrapper.junkyard = [];
  721. CallbackWrapper.factory = function(messageManager, channelName, listenerId, requestId) {
  722. var wrapper = CallbackWrapper.junkyard.pop();
  723. if ( wrapper ) {
  724. wrapper.init(messageManager, channelName, listenerId, requestId);
  725. return wrapper;
  726. }
  727. return new CallbackWrapper(messageManager, channelName, listenerId, requestId);
  728. };
  729. CallbackWrapper.prototype.init = function(messageManager, channelName, listenerId, requestId) {
  730. this.messageManager = messageManager;
  731. this.channelName = channelName;
  732. this.listenerId = listenerId;
  733. this.requestId = requestId;
  734. };
  735. CallbackWrapper.prototype.proxy = function(response) {
  736. var message = JSON.stringify({
  737. requestId: this.requestId,
  738. channelName: this.channelName,
  739. msg: response !== undefined ? response : null
  740. });
  741. if ( this.messageManager.sendAsyncMessage ) {
  742. this.messageManager.sendAsyncMessage(this.listenerId, message);
  743. } else {
  744. this.messageManager.broadcastAsyncMessage(this.listenerId, message);
  745. }
  746. // Mark for reuse
  747. this.messageManager =
  748. this.channelName =
  749. this.requestId =
  750. this.listenerId = null;
  751. CallbackWrapper.junkyard.push(this);
  752. };
  753. /******************************************************************************/
  754. var httpRequestHeadersFactory = function(channel) {
  755. var entry = httpRequestHeadersFactory.junkyard.pop();
  756. if ( entry ) {
  757. return entry.init(channel);
  758. }
  759. return new HTTPRequestHeaders(channel);
  760. };
  761. httpRequestHeadersFactory.junkyard = [];
  762. var HTTPRequestHeaders = function(channel) {
  763. this.init(channel);
  764. };
  765. HTTPRequestHeaders.prototype.init = function(channel) {
  766. this.channel = channel;
  767. return this;
  768. };
  769. HTTPRequestHeaders.prototype.dispose = function() {
  770. this.channel = null;
  771. httpRequestHeadersFactory.junkyard.push(this);
  772. };
  773. HTTPRequestHeaders.prototype.getHeader = function(name) {
  774. try {
  775. return this.channel.getRequestHeader(name);
  776. } catch (e) {
  777. }
  778. return '';
  779. };
  780. HTTPRequestHeaders.prototype.setHeader = function(name, newValue, create) {
  781. var oldValue = this.getHeader(name);
  782. if ( newValue === oldValue ) {
  783. return false;
  784. }
  785. if ( oldValue === '' && create !== true ) {
  786. return false;
  787. }
  788. this.channel.setRequestHeader(name, newValue, false);
  789. return true;
  790. };
  791. /******************************************************************************/
  792. var httpObserver = {
  793. classDescription: 'net-channel-event-sinks for ' + location.host,
  794. classID: Components.ID('{5d2e2797-6d68-42e2-8aeb-81ce6ba16b95}'),
  795. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  796. REQDATAKEY: location.host + 'reqdata',
  797. ABORT: Components.results.NS_BINDING_ABORTED,
  798. ACCEPT: Components.results.NS_SUCCEEDED,
  799. // Request types: https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIContentPolicy#Constants
  800. frameTypeMap: {
  801. 6: 'main_frame',
  802. 7: 'sub_frame'
  803. },
  804. typeMap: {
  805. 1: 'other',
  806. 2: 'script',
  807. 3: 'image',
  808. 4: 'stylesheet',
  809. 5: 'object',
  810. 6: 'main_frame',
  811. 7: 'sub_frame',
  812. 10: 'ping',
  813. 11: 'xmlhttprequest',
  814. 12: 'object',
  815. 14: 'font',
  816. 16: 'websocket',
  817. 21: 'image'
  818. },
  819. get componentRegistrar() {
  820. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  821. },
  822. get categoryManager() {
  823. return Cc['@mozilla.org/categorymanager;1']
  824. .getService(Ci.nsICategoryManager);
  825. },
  826. QueryInterface: (function() {
  827. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  828. return XPCOMUtils.generateQI([
  829. Ci.nsIFactory,
  830. Ci.nsIObserver,
  831. Ci.nsIChannelEventSink,
  832. Ci.nsISupportsWeakReference
  833. ]);
  834. })(),
  835. createInstance: function(outer, iid) {
  836. if ( outer ) {
  837. throw Components.results.NS_ERROR_NO_AGGREGATION;
  838. }
  839. return this.QueryInterface(iid);
  840. },
  841. register: function() {
  842. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  843. Services.obs.addObserver(this, 'http-on-opening-request', true);
  844. Services.obs.addObserver(this, 'http-on-modify-request', true);
  845. Services.obs.addObserver(this, 'http-on-examine-response', true);
  846. Services.obs.addObserver(this, 'http-on-examine-cached-response', true);
  847. // Guard against stale instances not having been unregistered
  848. if ( this.componentRegistrar.isCIDRegistered(this.classID) ) {
  849. try {
  850. this.componentRegistrar.unregisterFactory(this.classID, Components.manager.getClassObject(this.classID, Ci.nsIFactory));
  851. } catch (ex) {
  852. console.error('uMatrix> httpObserver > unable to unregister stale instance: ', ex);
  853. }
  854. }
  855. this.componentRegistrar.registerFactory(
  856. this.classID,
  857. this.classDescription,
  858. this.contractID,
  859. this
  860. );
  861. this.categoryManager.addCategoryEntry(
  862. 'net-channel-event-sinks',
  863. this.contractID,
  864. this.contractID,
  865. false,
  866. true
  867. );
  868. },
  869. unregister: function() {
  870. Services.obs.removeObserver(this, 'http-on-opening-request');
  871. Services.obs.removeObserver(this, 'http-on-modify-request');
  872. Services.obs.removeObserver(this, 'http-on-examine-response');
  873. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  874. this.componentRegistrar.unregisterFactory(this.classID, this);
  875. this.categoryManager.deleteCategoryEntry(
  876. 'net-channel-event-sinks',
  877. this.contractID,
  878. false
  879. );
  880. },
  881. handleRequest: function(channel, URI, tabId, rawtype) {
  882. var type = this.typeMap[rawtype] || 'other';
  883. var onBeforeRequest = vAPI.net.onBeforeRequest;
  884. if ( onBeforeRequest.types && onBeforeRequest.types.has(type) === false ) {
  885. return false;
  886. }
  887. var result = onBeforeRequest.callback({
  888. hostname: URI.asciiHost,
  889. parentFrameId: type === 'main_frame' ? -1 : 0,
  890. tabId: tabId,
  891. type: type,
  892. url: URI.asciiSpec
  893. });
  894. if ( typeof result !== 'object' ) {
  895. return false;
  896. }
  897. channel.cancel(this.ABORT);
  898. return true;
  899. },
  900. handleRequestHeaders: function(channel, URI, tabId, rawtype) {
  901. var type = this.typeMap[rawtype] || 'other';
  902. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  903. if ( onBeforeSendHeaders.types && onBeforeSendHeaders.types.has(type) === false ) {
  904. return;
  905. }
  906. var requestHeaders = httpRequestHeadersFactory(channel);
  907. onBeforeSendHeaders.callback({
  908. hostname: URI.asciiHost,
  909. parentFrameId: type === 'main_frame' ? -1 : 0,
  910. requestHeaders: requestHeaders,
  911. tabId: tabId,
  912. type: type,
  913. url: URI.asciiSpec
  914. });
  915. requestHeaders.dispose();
  916. },
  917. channelDataFromChannel: function(channel) {
  918. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  919. try {
  920. return channel.getProperty(this.REQDATAKEY);
  921. } catch (ex) {
  922. }
  923. }
  924. return null;
  925. },
  926. // https://github.com/gorhill/uMatrix/issues/165
  927. // https://developer.mozilla.org/en-US/Firefox/Releases/3.5/Updating_extensions#Getting_a_load_context_from_a_request
  928. // Not sure `umatrix:shouldLoad` is still needed, uMatrix does not
  929. // care about embedded frames topography.
  930. // Also:
  931. // https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Limitations_of_chrome_scripts
  932. tabIdFromChannel: function(channel) {
  933. var aWindow;
  934. if ( channel.notificationCallbacks ) {
  935. try {
  936. var loadContext = channel
  937. .notificationCallbacks
  938. .getInterface(Ci.nsILoadContext);
  939. if ( loadContext.topFrameElement ) {
  940. return vAPI.tabs.getTabId(loadContext.topFrameElement);
  941. }
  942. aWindow = loadContext.associatedWindow;
  943. } catch (ex) {
  944. //console.error(ex);
  945. }
  946. }
  947. try {
  948. if ( !aWindow && channel.loadGroup && channel.loadGroup.notificationCallbacks ) {
  949. aWindow = channel
  950. .loadGroup
  951. .notificationCallbacks
  952. .getInterface(Ci.nsILoadContext)
  953. .associatedWindow;
  954. }
  955. if ( aWindow ) {
  956. return vAPI.tabs.getTabId(aWindow
  957. .QueryInterface(Ci.nsIInterfaceRequestor)
  958. .getInterface(Ci.nsIWebNavigation)
  959. .QueryInterface(Ci.nsIDocShell)
  960. .rootTreeItem
  961. .QueryInterface(Ci.nsIInterfaceRequestor)
  962. .getInterface(Ci.nsIDOMWindow)
  963. .gBrowser
  964. .getBrowserForContentWindow(aWindow)
  965. );
  966. }
  967. } catch (ex) {
  968. //console.error(ex);
  969. }
  970. return vAPI.noTabId;
  971. },
  972. observe: function(channel, topic) {
  973. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  974. return;
  975. }
  976. var URI = channel.URI;
  977. var channelData, tabId, rawtype;
  978. if (
  979. topic === 'http-on-examine-response' ||
  980. topic === 'http-on-examine-cached-response'
  981. ) {
  982. channelData = this.channelDataFromChannel(channel);
  983. if ( channelData === null ) {
  984. return;
  985. }
  986. var type = this.frameTypeMap[channelData[1]];
  987. if ( !type ) {
  988. return;
  989. }
  990. topic = 'Content-Security-Policy';
  991. var result;
  992. try {
  993. result = channel.getResponseHeader(topic);
  994. } catch (ex) {
  995. result = null;
  996. }
  997. result = vAPI.net.onHeadersReceived.callback({
  998. hostname: URI.asciiHost,
  999. parentFrameId: type === 'main_frame' ? -1 : 0,
  1000. responseHeaders: result ? [{name: topic, value: result}] : [],
  1001. tabId: channelData[0],
  1002. type: type,
  1003. url: URI.asciiSpec
  1004. });
  1005. if ( result ) {
  1006. channel.setResponseHeader(
  1007. topic,
  1008. result.responseHeaders.pop().value,
  1009. true
  1010. );
  1011. }
  1012. return;
  1013. }
  1014. if ( topic === 'http-on-modify-request' ) {
  1015. channelData = this.channelDataFromChannel(channel);
  1016. if ( channelData === null ) {
  1017. return;
  1018. }
  1019. this.handleRequestHeaders(channel, URI, channelData[0], channelData[1]);
  1020. return;
  1021. }
  1022. // http-on-opening-request
  1023. tabId = this.tabIdFromChannel(channel);
  1024. rawtype = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  1025. if ( this.handleRequest(channel, URI, tabId, rawtype) === true ) {
  1026. return;
  1027. }
  1028. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1029. return;
  1030. }
  1031. // Carry data for behind-the-scene redirects
  1032. channel.setProperty(this.REQDATAKEY, [tabId, rawtype]);
  1033. },
  1034. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1035. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1036. var result = this.ACCEPT;
  1037. // If error thrown, the redirect will fail
  1038. try {
  1039. var URI = newChannel.URI;
  1040. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1041. return;
  1042. }
  1043. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1044. return;
  1045. }
  1046. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1047. if ( this.handleRequest(newChannel, URI, channelData[0], channelData[1]) ) {
  1048. result = this.ABORT;
  1049. return;
  1050. }
  1051. // Carry the data on in case of multiple redirects
  1052. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1053. newChannel.setProperty(this.REQDATAKEY, channelData);
  1054. }
  1055. } catch (ex) {
  1056. // console.error(ex);
  1057. } finally {
  1058. callback.onRedirectVerifyCallback(result);
  1059. }
  1060. }
  1061. };
  1062. /******************************************************************************/
  1063. vAPI.net = {};
  1064. /******************************************************************************/
  1065. vAPI.net.registerListeners = function() {
  1066. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1067. new Set(this.onBeforeRequest.types) :
  1068. null;
  1069. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1070. new Set(this.onBeforeSendHeaders.types) :
  1071. null;
  1072. var locationChangedListenerMessageName = location.host + ':locationChanged';
  1073. var locationChangedListener = function(e) {
  1074. var details = e.data;
  1075. var browser = e.target;
  1076. var tabId = vAPI.tabs.getTabId(browser);
  1077. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  1078. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  1079. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  1080. vAPI.tabs.onUpdated(tabId, {url: details.url}, {
  1081. frameId: 0,
  1082. tabId: tabId,
  1083. url: browser.currentURI.asciiSpec
  1084. });
  1085. return;
  1086. }
  1087. // https://github.com/chrisaljoudi/uBlock/issues/105
  1088. // Allow any kind of pages
  1089. vAPI.tabs.onNavigation({ frameId: 0, tabId: tabId, url: details.url });
  1090. };
  1091. vAPI.messaging.globalMessageManager.addMessageListener(
  1092. locationChangedListenerMessageName,
  1093. locationChangedListener
  1094. );
  1095. httpObserver.register();
  1096. cleanupTasks.push(function() {
  1097. vAPI.messaging.globalMessageManager.removeMessageListener(
  1098. locationChangedListenerMessageName,
  1099. locationChangedListener
  1100. );
  1101. httpObserver.unregister();
  1102. });
  1103. };
  1104. /******************************************************************************/
  1105. vAPI.toolbarButton = {
  1106. id: location.host + '-button',
  1107. type: 'view',
  1108. viewId: location.host + '-panel',
  1109. label: vAPI.app.name,
  1110. tooltiptext: vAPI.app.name,
  1111. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1112. };
  1113. /******************************************************************************/
  1114. // Toolbar button UI for desktop Firefox
  1115. vAPI.toolbarButton.init = function() {
  1116. var CustomizableUI;
  1117. try {
  1118. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1119. } catch (ex) {
  1120. return;
  1121. }
  1122. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1123. this.styleURI = [
  1124. '#' + this.id + ' {',
  1125. 'list-style-image: url(',
  1126. vAPI.getURL('img/browsericons/icon19-off.png'),
  1127. ');',
  1128. '}',
  1129. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1130. 'width: 160px;',
  1131. 'height: 290px;',
  1132. 'overflow: hidden !important;',
  1133. '}'
  1134. ];
  1135. var platformVersion = Services.appinfo.platformVersion;
  1136. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1137. this.styleURI.push(
  1138. '#' + this.id + '[badge]:not([badge=""])::after {',
  1139. 'position: absolute;',
  1140. 'margin-left: -16px;',
  1141. 'margin-top: 3px;',
  1142. 'padding: 1px 2px;',
  1143. 'font-size: 9px;',
  1144. 'font-weight: bold;',
  1145. 'color: #fff;',
  1146. 'background: #000;',
  1147. 'content: attr(badge);',
  1148. '}'
  1149. );
  1150. } else {
  1151. this.CUIEvents = {};
  1152. var updateBadge = function() {
  1153. var wId = vAPI.toolbarButton.id;
  1154. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1155. for ( var win of vAPI.tabs.getWindows() ) {
  1156. var button = win.document.getElementById(wId);
  1157. if ( buttonInPanel ) {
  1158. button.classList.remove('badged-button');
  1159. continue;
  1160. }
  1161. if ( button === null ) {
  1162. continue;
  1163. }
  1164. button.classList.add('badged-button');
  1165. }
  1166. if ( buttonInPanel ) {
  1167. return;
  1168. }
  1169. // Anonymous elements need some time to be reachable
  1170. vAPI.setTimeout(this.updateBadgeStyle, 250);
  1171. }.bind(this.CUIEvents);
  1172. this.CUIEvents.onCustomizeEnd = updateBadge;
  1173. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1174. this.CUIEvents.updateBadgeStyle = function() {
  1175. var css = [
  1176. 'background: #000',
  1177. 'color: #fff'
  1178. ].join(';');
  1179. for ( var win of vAPI.tabs.getWindows() ) {
  1180. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1181. if ( button === null ) {
  1182. continue;
  1183. }
  1184. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1185. button,
  1186. 'class',
  1187. 'toolbarbutton-badge'
  1188. );
  1189. if ( !badge ) {
  1190. return;
  1191. }
  1192. badge.style.cssText = css;
  1193. }
  1194. };
  1195. this.onCreated = function(button) {
  1196. button.setAttribute('badge', '');
  1197. vAPI.setTimeout(updateBadge, 250);
  1198. };
  1199. CustomizableUI.addListener(this.CUIEvents);
  1200. }
  1201. this.styleURI = Services.io.newURI(
  1202. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1203. null,
  1204. null
  1205. );
  1206. this.closePopup = function({target}) {
  1207. CustomizableUI.hidePanelForNode(
  1208. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1209. );
  1210. };
  1211. CustomizableUI.createWidget(this);
  1212. vAPI.messaging.globalMessageManager.addMessageListener(
  1213. location.host + ':closePopup',
  1214. this.closePopup
  1215. );
  1216. cleanupTasks.push(function() {
  1217. if ( this.CUIEvents ) {
  1218. CustomizableUI.removeListener(this.CUIEvents);
  1219. }
  1220. CustomizableUI.destroyWidget(this.id);
  1221. vAPI.messaging.globalMessageManager.removeMessageListener(
  1222. location.host + ':closePopup',
  1223. this.closePopup
  1224. );
  1225. for ( var win of vAPI.tabs.getWindows() ) {
  1226. var panel = win.document.getElementById(this.viewId);
  1227. panel.parentNode.removeChild(panel);
  1228. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1229. .getInterface(Ci.nsIDOMWindowUtils)
  1230. .removeSheet(this.styleURI, 1);
  1231. }
  1232. }.bind(this));
  1233. this.init = null;
  1234. };
  1235. /******************************************************************************/
  1236. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1237. var panel = doc.createElement('panelview');
  1238. panel.setAttribute('id', this.viewId);
  1239. var iframe = doc.createElement('iframe');
  1240. iframe.setAttribute('type', 'content');
  1241. iframe.setAttribute('overflow-x', 'hidden');
  1242. doc.getElementById('PanelUI-multiView')
  1243. .appendChild(panel)
  1244. .appendChild(iframe);
  1245. var updateTimer = null;
  1246. var delayedResize = function() {
  1247. if ( updateTimer ) {
  1248. return;
  1249. }
  1250. updateTimer = vAPI.setTimeout(resizePopup, 10);
  1251. };
  1252. var resizePopup = function() {
  1253. updateTimer = null;
  1254. var body = iframe.contentDocument.body;
  1255. panel.parentNode.style.maxWidth = 'none';
  1256. // We set a limit for height
  1257. var height = Math.min(body.clientHeight, 600);
  1258. var width = body.clientWidth;
  1259. // https://github.com/chrisaljoudi/uBlock/issues/730
  1260. // Voodoo programming: this recipe works
  1261. panel.style.setProperty('height', height + 'px');
  1262. iframe.style.setProperty('height', height + 'px');
  1263. // Adjust width for presence/absence of vertical scroll bar which may
  1264. // have appeared as a result of last operation.
  1265. panel.style.setProperty('width', width + 'px');
  1266. var cw = panel.clientWidth;
  1267. var dw = iframe.contentWindow.document.documentElement.clientWidth;
  1268. if ( cw !== dw ) {
  1269. width = 2 * cw - dw;
  1270. panel.style.setProperty('width', width + 'px');
  1271. }
  1272. if ( iframe.clientHeight !== height || panel.clientWidth !== width ) {
  1273. delayedResize();
  1274. return;
  1275. }
  1276. };
  1277. var onPopupReady = function() {
  1278. var win = this.contentWindow;
  1279. if ( !win || win.location.host !== location.host ) {
  1280. return;
  1281. }
  1282. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1283. attributes: true,
  1284. characterData: true,
  1285. subtree: true
  1286. });
  1287. delayedResize();
  1288. };
  1289. iframe.addEventListener('load', onPopupReady, true);
  1290. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1291. .getInterface(Ci.nsIDOMWindowUtils)
  1292. .loadSheet(this.styleURI, 1);
  1293. };
  1294. /******************************************************************************/
  1295. vAPI.toolbarButton.onViewShowing = function({target}) {
  1296. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1297. };
  1298. /******************************************************************************/
  1299. vAPI.toolbarButton.onViewHiding = function({target}) {
  1300. target.parentNode.style.maxWidth = '';
  1301. target.firstChild.setAttribute('src', 'about:blank');
  1302. };
  1303. /******************************************************************************/
  1304. vAPI.toolbarButton.updateState = function(win, tabId) {
  1305. var button = win.document.getElementById(this.id);
  1306. if ( !button ) {
  1307. return;
  1308. }
  1309. var icon = this.tabs[tabId];
  1310. button.setAttribute('badge', icon && icon.badge || '');
  1311. var iconId = icon && icon.img ? icon.img : 'off';
  1312. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1313. button.style.listStyleImage = icon;
  1314. };
  1315. /******************************************************************************/
  1316. vAPI.toolbarButton.init();
  1317. /******************************************************************************/
  1318. /******************************************************************************/
  1319. vAPI.contextMenu = {
  1320. contextMap: {
  1321. frame: 'inFrame',
  1322. link: 'onLink',
  1323. image: 'onImage',
  1324. audio: 'onAudio',
  1325. video: 'onVideo',
  1326. editable: 'onEditableArea'
  1327. }
  1328. };
  1329. /******************************************************************************/
  1330. vAPI.contextMenu.displayMenuItem = function({target}) {
  1331. var doc = target.ownerDocument;
  1332. var gContextMenu = doc.defaultView.gContextMenu;
  1333. if ( !gContextMenu.browser ) {
  1334. return;
  1335. }
  1336. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1337. var currentURI = gContextMenu.browser.currentURI;
  1338. // https://github.com/chrisaljoudi/uBlock/issues/105
  1339. // TODO: Should the element picker works on any kind of pages?
  1340. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1341. menuitem.hidden = true;
  1342. return;
  1343. }
  1344. var ctx = vAPI.contextMenu.contexts;
  1345. if ( !ctx ) {
  1346. menuitem.hidden = false;
  1347. return;
  1348. }
  1349. var ctxMap = vAPI.contextMenu.contextMap;
  1350. for ( var context of ctx ) {
  1351. if (
  1352. context === 'page' &&
  1353. !gContextMenu.onLink &&
  1354. !gContextMenu.onImage &&
  1355. !gContextMenu.onEditableArea &&
  1356. !gContextMenu.inFrame &&
  1357. !gContextMenu.onVideo &&
  1358. !gContextMenu.onAudio
  1359. ) {
  1360. menuitem.hidden = false;
  1361. return;
  1362. }
  1363. if ( gContextMenu[ctxMap[context]] ) {
  1364. menuitem.hidden = false;
  1365. return;
  1366. }
  1367. }
  1368. menuitem.hidden = true;
  1369. };
  1370. /******************************************************************************/
  1371. vAPI.contextMenu.register = function(doc) {
  1372. if ( !this.menuItemId ) {
  1373. return;
  1374. }
  1375. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1376. var menuitem = doc.createElement('menuitem');
  1377. menuitem.setAttribute('id', this.menuItemId);
  1378. menuitem.setAttribute('label', this.menuLabel);
  1379. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1380. menuitem.setAttribute('class', 'menuitem-iconic');
  1381. menuitem.addEventListener('command', this.onCommand);
  1382. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1383. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1384. };
  1385. /******************************************************************************/
  1386. vAPI.contextMenu.unregister = function(doc) {
  1387. if ( !this.menuItemId ) {
  1388. return;
  1389. }
  1390. var menuitem = doc.getElementById(this.menuItemId);
  1391. var contextMenu = menuitem.parentNode;
  1392. menuitem.removeEventListener('command', this.onCommand);
  1393. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1394. contextMenu.removeChild(menuitem);
  1395. };
  1396. /******************************************************************************/
  1397. vAPI.contextMenu.create = function(details, callback) {
  1398. this.menuItemId = details.id;
  1399. this.menuLabel = details.title;
  1400. this.contexts = details.contexts;
  1401. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1402. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1403. } else {
  1404. // default in Chrome
  1405. this.contexts = ['page'];
  1406. }
  1407. this.onCommand = function() {
  1408. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1409. var details = {
  1410. menuItemId: this.id
  1411. };
  1412. if ( gContextMenu.inFrame ) {
  1413. details.tagName = 'iframe';
  1414. // Probably won't work with e10s
  1415. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1416. } else if ( gContextMenu.onImage ) {
  1417. details.tagName = 'img';
  1418. details.srcUrl = gContextMenu.mediaURL;
  1419. } else if ( gContextMenu.onAudio ) {
  1420. details.tagName = 'audio';
  1421. details.srcUrl = gContextMenu.mediaURL;
  1422. } else if ( gContextMenu.onVideo ) {
  1423. details.tagName = 'video';
  1424. details.srcUrl = gContextMenu.mediaURL;
  1425. } else if ( gContextMenu.onLink ) {
  1426. details.tagName = 'a';
  1427. details.linkUrl = gContextMenu.linkURL;
  1428. }
  1429. callback(details, {
  1430. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1431. url: gContextMenu.browser.currentURI.asciiSpec
  1432. });
  1433. };
  1434. for ( var win of vAPI.tabs.getWindows() ) {
  1435. this.register(win.document);
  1436. }
  1437. };
  1438. /******************************************************************************/
  1439. vAPI.contextMenu.remove = function() {
  1440. for ( var win of vAPI.tabs.getWindows() ) {
  1441. this.unregister(win.document);
  1442. }
  1443. this.menuItemId = null;
  1444. this.menuLabel = null;
  1445. this.contexts = null;
  1446. this.onCommand = null;
  1447. };
  1448. /******************************************************************************/
  1449. /******************************************************************************/
  1450. var optionsObserver = {
  1451. addonId: 'uMatrix@raymondhill.net',
  1452. register: function() {
  1453. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1454. cleanupTasks.push(this.unregister.bind(this));
  1455. var browser = getBrowserForTab(vAPI.tabs.get(null));
  1456. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1457. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1458. }
  1459. },
  1460. unregister: function() {
  1461. Services.obs.removeObserver(this, 'addon-options-displayed');
  1462. },
  1463. setupOptionsButton: function(doc, id, page) {
  1464. var button = doc.getElementById(id);
  1465. if ( button === null ) {
  1466. return;
  1467. }
  1468. button.addEventListener('command', function() {
  1469. vAPI.tabs.open({ url: page, index: -1 });
  1470. });
  1471. button.label = vAPI.i18n(id);
  1472. },
  1473. observe: function(doc, topic, addonId) {
  1474. if ( addonId !== this.addonId ) {
  1475. return;
  1476. }
  1477. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1478. this.setupOptionsButton(doc, 'showLoggerButton', 'logger-ui.html');
  1479. }
  1480. };
  1481. optionsObserver.register();
  1482. /******************************************************************************/
  1483. /******************************************************************************/
  1484. vAPI.lastError = function() {
  1485. return null;
  1486. };
  1487. /******************************************************************************/
  1488. /******************************************************************************/
  1489. // This is called only once, when everything has been loaded in memory after
  1490. // the extension was launched. It can be used to inject content scripts
  1491. // in already opened web pages, to remove whatever nuisance could make it to
  1492. // the web pages before uBlock was ready.
  1493. vAPI.onLoadAllCompleted = function() {
  1494. for ( var tab of this.tabs.getAllSync() ) {
  1495. // We're insterested in only the tabs that were already loaded
  1496. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  1497. location.host + '-load-completed'
  1498. );
  1499. }
  1500. };
  1501. /******************************************************************************/
  1502. /******************************************************************************/
  1503. // Likelihood is that we do not have to punycode: given punycode overhead,
  1504. // it's faster to check and skip than do it unconditionally all the time.
  1505. var punycodeHostname = punycode.toASCII;
  1506. var isNotASCII = /[^\x21-\x7F]/;
  1507. vAPI.punycodeHostname = function(hostname) {
  1508. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1509. };
  1510. vAPI.punycodeURL = function(url) {
  1511. if ( isNotASCII.test(url) ) {
  1512. return Services.io.newURI(url, null, null).asciiSpec;
  1513. }
  1514. return url;
  1515. };
  1516. /******************************************************************************/
  1517. /******************************************************************************/
  1518. vAPI.browserData = {};
  1519. /******************************************************************************/
  1520. // https://developer.mozilla.org/en-US/docs/HTTP_Cache
  1521. vAPI.browserData.clearCache = function(callback) {
  1522. // PURGE_DISK_DATA_ONLY:1
  1523. // PURGE_DISK_ALL:2
  1524. // PURGE_EVERYTHING:3
  1525. // However I verified that not argument does clear the cache data.
  1526. Services.cache2.clear();
  1527. if ( typeof callback === 'function' ) {
  1528. callback();
  1529. }
  1530. };
  1531. /******************************************************************************/
  1532. vAPI.browserData.clearOrigin = function(/* domain */) {
  1533. // TODO
  1534. };
  1535. /******************************************************************************/
  1536. /******************************************************************************/
  1537. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager2
  1538. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  1539. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  1540. vAPI.cookies = {};
  1541. /******************************************************************************/
  1542. vAPI.cookies.CookieEntry = function(ffCookie) {
  1543. this.domain = ffCookie.host;
  1544. this.name = ffCookie.name;
  1545. this.path = ffCookie.path;
  1546. this.secure = ffCookie.isSecure === true;
  1547. this.session = ffCookie.expires === 0;
  1548. this.value = ffCookie.value;
  1549. };
  1550. /******************************************************************************/
  1551. vAPI.cookies.start = function() {
  1552. Services.obs.addObserver(this, 'cookie-changed', false);
  1553. cleanupTasks.push(this.stop.bind(this));
  1554. };
  1555. /******************************************************************************/
  1556. vAPI.cookies.stop = function() {
  1557. Services.obs.removeObserver(this, 'cookie-changed');
  1558. };
  1559. /******************************************************************************/
  1560. vAPI.cookies.observe = function(subject, topic, reason) {
  1561. if ( topic !== 'cookie-changed' ) {
  1562. return;
  1563. }
  1564. if ( reason === 'deleted' || subject instanceof Ci.nsICookie2 === false ) {
  1565. return;
  1566. }
  1567. if ( typeof this.onChanged === 'function' ) {
  1568. this.onChanged(new this.CookieEntry(subject));
  1569. }
  1570. };
  1571. /******************************************************************************/
  1572. // Meant and expected to be asynchronous.
  1573. vAPI.cookies.getAll = function(callback) {
  1574. if ( typeof callback !== 'function' ) {
  1575. return;
  1576. }
  1577. var onAsync = function() {
  1578. var out = [];
  1579. var enumerator = Services.cookies.enumerator;
  1580. var ffcookie;
  1581. while ( enumerator.hasMoreElements() ) {
  1582. ffcookie = enumerator.getNext();
  1583. if ( ffcookie instanceof Ci.nsICookie ) {
  1584. out.push(new this.CookieEntry(ffcookie));
  1585. }
  1586. }
  1587. callback(out);
  1588. };
  1589. vAPI.setTimeout(onAsync.bind(this), 0);
  1590. };
  1591. /******************************************************************************/
  1592. vAPI.cookies.remove = function(details, callback) {
  1593. var uri = Services.io.newURI(details.url, null, null);
  1594. var cookies = Services.cookies;
  1595. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  1596. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  1597. if ( typeof callback === 'function' ) {
  1598. callback({
  1599. domain: uri.asciiHost,
  1600. name: details.name,
  1601. path: uri.path
  1602. });
  1603. }
  1604. };
  1605. /******************************************************************************/
  1606. /******************************************************************************/
  1607. })();
  1608. /******************************************************************************/