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.

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