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.

2047 lines
60 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
  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. // onPopup - handled in httpObserver.handlePopup
  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. 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('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  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. lastRequest: [{}, {}],
  820. get componentRegistrar() {
  821. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  822. },
  823. get categoryManager() {
  824. return Cc['@mozilla.org/categorymanager;1']
  825. .getService(Ci.nsICategoryManager);
  826. },
  827. QueryInterface: (function() {
  828. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  829. return XPCOMUtils.generateQI([
  830. Ci.nsIFactory,
  831. Ci.nsIObserver,
  832. Ci.nsIChannelEventSink,
  833. Ci.nsISupportsWeakReference
  834. ]);
  835. })(),
  836. createInstance: function(outer, iid) {
  837. if ( outer ) {
  838. throw Components.results.NS_ERROR_NO_AGGREGATION;
  839. }
  840. return this.QueryInterface(iid);
  841. },
  842. register: function() {
  843. // https://developer.mozilla.org/en/docs/Observer_Notifications#HTTP_requests
  844. Services.obs.addObserver(this, 'http-on-opening-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-examine-response');
  872. Services.obs.removeObserver(this, 'http-on-examine-cached-response');
  873. this.componentRegistrar.unregisterFactory(this.classID, this);
  874. this.categoryManager.deleteCategoryEntry(
  875. 'net-channel-event-sinks',
  876. this.contractID,
  877. false
  878. );
  879. },
  880. handlePopup: function(URI, tabId, sourceTabId) {
  881. if ( !sourceTabId ) {
  882. return false;
  883. }
  884. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  885. return false;
  886. }
  887. var result = vAPI.tabs.onPopup({
  888. targetTabId: tabId,
  889. openerTabId: sourceTabId,
  890. targetURL: URI.asciiSpec
  891. });
  892. return result === true;
  893. },
  894. handleRequest: function(channel, URI, details) {
  895. var type = this.typeMap[details.type] || 'other';
  896. var result;
  897. var callbackDetails = {
  898. frameId: details.frameId,
  899. hostname: URI.asciiHost,
  900. parentFrameId: details.parentFrameId,
  901. tabId: details.tabId,
  902. type: type,
  903. url: URI.asciiSpec
  904. };
  905. var onBeforeRequest = vAPI.net.onBeforeRequest;
  906. if ( !onBeforeRequest.types || onBeforeRequest.types.has(type) ) {
  907. result = onBeforeRequest.callback(callbackDetails);
  908. if ( typeof result === 'object' && result.cancel === true ) {
  909. channel.cancel(this.ABORT);
  910. return true;
  911. }
  912. // For the time being, will block instead of redirecting
  913. // TODO: figure a better way of blocking embedded frames.
  914. // Maybe blocking network requests, then having a content script
  915. // revisit the DOM to replace blocked frame with something more
  916. // friendly. Will see.
  917. if ( typeof result === 'object' && result.redirectUrl ) {
  918. channel.cancel(this.ABORT);
  919. return true;
  920. }
  921. }
  922. var onBeforeSendHeaders = vAPI.net.onBeforeSendHeaders;
  923. if ( !onBeforeSendHeaders.types || onBeforeSendHeaders.types.has(type) ) {
  924. callbackDetails.requestHeaders = httpRequestHeadersFactory(channel);
  925. result = onBeforeSendHeaders.callback(callbackDetails);
  926. callbackDetails.requestHeaders.dispose();
  927. if ( typeof result === 'object' && result.cancel === true ) {
  928. channel.cancel(this.ABORT);
  929. return true;
  930. }
  931. }
  932. return false;
  933. },
  934. observe: function(channel, topic) {
  935. if ( channel instanceof Ci.nsIHttpChannel === false ) {
  936. return;
  937. }
  938. var URI = channel.URI;
  939. var channelData, type, result;
  940. if (
  941. topic === 'http-on-examine-response' ||
  942. topic === 'http-on-examine-cached-response'
  943. ) {
  944. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  945. return;
  946. }
  947. try {
  948. channelData = channel.getProperty(this.REQDATAKEY);
  949. } catch (ex) {
  950. return;
  951. }
  952. if ( !channelData ) {
  953. return;
  954. }
  955. type = this.frameTypeMap[channelData[4]];
  956. if ( !type ) {
  957. return;
  958. }
  959. topic = 'Content-Security-Policy';
  960. try {
  961. result = channel.getResponseHeader(topic);
  962. } catch (ex) {
  963. result = null;
  964. }
  965. result = vAPI.net.onHeadersReceived.callback({
  966. hostname: URI.asciiHost,
  967. parentFrameId: channelData[1],
  968. responseHeaders: result ? [{name: topic, value: result}] : [],
  969. tabId: channelData[3],
  970. type: type,
  971. url: URI.asciiSpec
  972. });
  973. if ( result ) {
  974. channel.setResponseHeader(
  975. topic,
  976. result.responseHeaders.pop().value,
  977. true
  978. );
  979. }
  980. return;
  981. }
  982. // http-on-opening-request
  983. var lastRequest = this.lastRequest[0];
  984. if ( lastRequest.url !== URI.spec ) {
  985. if ( this.lastRequest[1].url === URI.spec ) {
  986. lastRequest = this.lastRequest[1];
  987. } else {
  988. lastRequest.url = null;
  989. }
  990. }
  991. if ( lastRequest.url === null ) {
  992. lastRequest.type = channel.loadInfo && channel.loadInfo.contentPolicyType || 1;
  993. result = this.handleRequest(channel, URI, {
  994. tabId: vAPI.noTabId,
  995. type: lastRequest.type
  996. });
  997. if ( result === true ) {
  998. return;
  999. }
  1000. if ( channel instanceof Ci.nsIWritablePropertyBag === false ) {
  1001. return;
  1002. }
  1003. // Carry data for behind-the-scene redirects
  1004. channel.setProperty(
  1005. this.REQDATAKEY,
  1006. [lastRequest.type, vAPI.noTabId, null, 0, -1]
  1007. );
  1008. return;
  1009. }
  1010. // Important! When loading file via XHR for mirroring,
  1011. // the URL will be the same, so it could fall into an infinite loop
  1012. lastRequest.url = null;
  1013. if ( this.handleRequest(channel, URI, lastRequest) ) {
  1014. return;
  1015. }
  1016. // If request is not handled we may use the data in on-modify-request
  1017. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  1018. channel.setProperty(this.REQDATAKEY, [
  1019. lastRequest.frameId,
  1020. lastRequest.parentFrameId,
  1021. lastRequest.sourceTabId,
  1022. lastRequest.tabId,
  1023. lastRequest.type
  1024. ]);
  1025. }
  1026. },
  1027. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  1028. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  1029. var result = this.ACCEPT;
  1030. // If error thrown, the redirect will fail
  1031. try {
  1032. var URI = newChannel.URI;
  1033. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  1034. return;
  1035. }
  1036. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  1037. return;
  1038. }
  1039. var channelData = oldChannel.getProperty(this.REQDATAKEY);
  1040. if ( this.handlePopup(URI, channelData[3], channelData[2]) ) {
  1041. result = this.ABORT;
  1042. return;
  1043. }
  1044. var details = {
  1045. frameId: channelData[0],
  1046. parentFrameId: channelData[1],
  1047. tabId: channelData[3],
  1048. type: channelData[4]
  1049. };
  1050. if ( this.handleRequest(newChannel, URI, details) ) {
  1051. result = this.ABORT;
  1052. return;
  1053. }
  1054. // Carry the data on in case of multiple redirects
  1055. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  1056. newChannel.setProperty(this.REQDATAKEY, channelData);
  1057. }
  1058. } catch (ex) {
  1059. // console.error(ex);
  1060. } finally {
  1061. callback.onRedirectVerifyCallback(result);
  1062. }
  1063. }
  1064. };
  1065. /******************************************************************************/
  1066. vAPI.net = {};
  1067. /******************************************************************************/
  1068. vAPI.net.registerListeners = function() {
  1069. this.onBeforeRequest.types = this.onBeforeRequest.types ?
  1070. new Set(this.onBeforeRequest.types) :
  1071. null;
  1072. this.onBeforeSendHeaders.types = this.onBeforeSendHeaders.types ?
  1073. new Set(this.onBeforeSendHeaders.types) :
  1074. null;
  1075. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  1076. var shouldLoadListener = function(e) {
  1077. var details = e.data;
  1078. var tabId = vAPI.tabs.getTabId(e.target);
  1079. var sourceTabId = null;
  1080. // Popup candidate
  1081. if ( details.openerURL ) {
  1082. for ( var tab of vAPI.tabs.getAllSync() ) {
  1083. var URI = getBrowserForTab(tab).currentURI;
  1084. // Probably isn't the best method to identify the source tab
  1085. if ( URI.spec !== details.openerURL ) {
  1086. continue;
  1087. }
  1088. sourceTabId = vAPI.tabs.getTabId(tab);
  1089. if ( sourceTabId === tabId ) {
  1090. sourceTabId = null;
  1091. continue;
  1092. }
  1093. URI = Services.io.newURI(details.url, null, null);
  1094. if ( httpObserver.handlePopup(URI, tabId, sourceTabId) ) {
  1095. return;
  1096. }
  1097. break;
  1098. }
  1099. }
  1100. var lastRequest = httpObserver.lastRequest;
  1101. lastRequest[1] = lastRequest[0];
  1102. lastRequest[0] = {
  1103. frameId: details.frameId,
  1104. parentFrameId: details.parentFrameId,
  1105. sourceTabId: sourceTabId,
  1106. tabId: tabId,
  1107. type: details.type,
  1108. url: details.url
  1109. };
  1110. };
  1111. vAPI.messaging.globalMessageManager.addMessageListener(
  1112. shouldLoadListenerMessageName,
  1113. shouldLoadListener
  1114. );
  1115. var locationChangedListenerMessageName = location.host + ':locationChanged';
  1116. var locationChangedListener = function(e) {
  1117. var details = e.data;
  1118. var browser = e.target;
  1119. var tabId = vAPI.tabs.getTabId(browser);
  1120. //console.debug("nsIWebProgressListener: onLocationChange: " + details.url + " (" + details.flags + ")");
  1121. // LOCATION_CHANGE_SAME_DOCUMENT = "did not load a new document"
  1122. if ( details.flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT ) {
  1123. vAPI.tabs.onUpdated(tabId, {url: details.url}, {
  1124. frameId: 0,
  1125. tabId: tabId,
  1126. url: browser.currentURI.asciiSpec
  1127. });
  1128. return;
  1129. }
  1130. // https://github.com/chrisaljoudi/uBlock/issues/105
  1131. // Allow any kind of pages
  1132. vAPI.tabs.onNavigation({
  1133. frameId: 0,
  1134. tabId: tabId,
  1135. url: details.url,
  1136. });
  1137. };
  1138. vAPI.messaging.globalMessageManager.addMessageListener(
  1139. locationChangedListenerMessageName,
  1140. locationChangedListener
  1141. );
  1142. httpObserver.register();
  1143. cleanupTasks.push(function() {
  1144. vAPI.messaging.globalMessageManager.removeMessageListener(
  1145. shouldLoadListenerMessageName,
  1146. shouldLoadListener
  1147. );
  1148. vAPI.messaging.globalMessageManager.removeMessageListener(
  1149. locationChangedListenerMessageName,
  1150. locationChangedListener
  1151. );
  1152. httpObserver.unregister();
  1153. });
  1154. };
  1155. /******************************************************************************/
  1156. vAPI.toolbarButton = {
  1157. id: location.host + '-button',
  1158. type: 'view',
  1159. viewId: location.host + '-panel',
  1160. label: vAPI.app.name,
  1161. tooltiptext: vAPI.app.name,
  1162. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  1163. };
  1164. /******************************************************************************/
  1165. // Toolbar button UI for desktop Firefox
  1166. vAPI.toolbarButton.init = function() {
  1167. var CustomizableUI;
  1168. try {
  1169. CustomizableUI = Cu.import('resource:///modules/CustomizableUI.jsm', null).CustomizableUI;
  1170. } catch (ex) {
  1171. return;
  1172. }
  1173. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  1174. this.styleURI = [
  1175. '#' + this.id + ' {',
  1176. 'list-style-image: url(',
  1177. vAPI.getURL('img/browsericons/icon19-off.png'),
  1178. ');',
  1179. '}',
  1180. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  1181. 'width: 160px;',
  1182. 'height: 290px;',
  1183. 'overflow: hidden !important;',
  1184. '}'
  1185. ];
  1186. var platformVersion = Services.appinfo.platformVersion;
  1187. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1188. this.styleURI.push(
  1189. '#' + this.id + '[badge]:not([badge=""])::after {',
  1190. 'position: absolute;',
  1191. 'margin-left: -16px;',
  1192. 'margin-top: 3px;',
  1193. 'padding: 1px 2px;',
  1194. 'font-size: 9px;',
  1195. 'font-weight: bold;',
  1196. 'color: #fff;',
  1197. 'background: #000;',
  1198. 'content: attr(badge);',
  1199. '}'
  1200. );
  1201. } else {
  1202. this.CUIEvents = {};
  1203. var updateBadge = function() {
  1204. var wId = vAPI.toolbarButton.id;
  1205. var buttonInPanel = CustomizableUI.getWidget(wId).areaType === CustomizableUI.TYPE_MENU_PANEL;
  1206. for ( var win of vAPI.tabs.getWindows() ) {
  1207. var button = win.document.getElementById(wId);
  1208. if ( buttonInPanel ) {
  1209. button.classList.remove('badged-button');
  1210. continue;
  1211. }
  1212. if ( button === null ) {
  1213. continue;
  1214. }
  1215. button.classList.add('badged-button');
  1216. }
  1217. if ( buttonInPanel ) {
  1218. return;
  1219. }
  1220. // Anonymous elements need some time to be reachable
  1221. setTimeout(this.updateBadgeStyle, 250);
  1222. }.bind(this.CUIEvents);
  1223. this.CUIEvents.onCustomizeEnd = updateBadge;
  1224. this.CUIEvents.onWidgetUnderflow = updateBadge;
  1225. this.CUIEvents.updateBadgeStyle = function() {
  1226. var css = [
  1227. 'background: #000',
  1228. 'color: #fff'
  1229. ].join(';');
  1230. for ( var win of vAPI.tabs.getWindows() ) {
  1231. var button = win.document.getElementById(vAPI.toolbarButton.id);
  1232. if ( button === null ) {
  1233. continue;
  1234. }
  1235. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1236. button,
  1237. 'class',
  1238. 'toolbarbutton-badge'
  1239. );
  1240. if ( !badge ) {
  1241. return;
  1242. }
  1243. badge.style.cssText = css;
  1244. }
  1245. };
  1246. this.onCreated = function(button) {
  1247. button.setAttribute('badge', '');
  1248. setTimeout(updateBadge, 250);
  1249. };
  1250. CustomizableUI.addListener(this.CUIEvents);
  1251. }
  1252. this.styleURI = Services.io.newURI(
  1253. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  1254. null,
  1255. null
  1256. );
  1257. this.closePopup = function({target}) {
  1258. CustomizableUI.hidePanelForNode(
  1259. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  1260. );
  1261. };
  1262. CustomizableUI.createWidget(this);
  1263. vAPI.messaging.globalMessageManager.addMessageListener(
  1264. location.host + ':closePopup',
  1265. this.closePopup
  1266. );
  1267. cleanupTasks.push(function() {
  1268. if ( this.CUIEvents ) {
  1269. CustomizableUI.removeListener(this.CUIEvents);
  1270. }
  1271. CustomizableUI.destroyWidget(this.id);
  1272. vAPI.messaging.globalMessageManager.removeMessageListener(
  1273. location.host + ':closePopup',
  1274. this.closePopup
  1275. );
  1276. for ( var win of vAPI.tabs.getWindows() ) {
  1277. var panel = win.document.getElementById(this.viewId);
  1278. panel.parentNode.removeChild(panel);
  1279. win.QueryInterface(Ci.nsIInterfaceRequestor)
  1280. .getInterface(Ci.nsIDOMWindowUtils)
  1281. .removeSheet(this.styleURI, 1);
  1282. }
  1283. }.bind(this));
  1284. this.init = null;
  1285. };
  1286. /******************************************************************************/
  1287. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  1288. var panel = doc.createElement('panelview');
  1289. panel.setAttribute('id', this.viewId);
  1290. var iframe = doc.createElement('iframe');
  1291. iframe.setAttribute('type', 'content');
  1292. doc.getElementById('PanelUI-multiView')
  1293. .appendChild(panel)
  1294. .appendChild(iframe);
  1295. var updateTimer = null;
  1296. var delayedResize = function() {
  1297. if ( updateTimer ) {
  1298. return;
  1299. }
  1300. updateTimer = setTimeout(resizePopup, 10);
  1301. };
  1302. var resizePopup = function() {
  1303. updateTimer = null;
  1304. var body = iframe.contentDocument.body;
  1305. panel.parentNode.style.maxWidth = 'none';
  1306. // We set a limit for height
  1307. var height = Math.min(body.clientHeight, 600);
  1308. var width = body.clientWidth;
  1309. // https://github.com/chrisaljoudi/uBlock/issues/730
  1310. // Voodoo programming: this recipe works
  1311. panel.style.height = iframe.style.height = height.toString() + 'px';
  1312. panel.style.width = iframe.style.width = width.toString() + 'px';
  1313. if ( iframe.clientHeight !== height || iframe.clientWidth !== width ) {
  1314. delayedResize();
  1315. }
  1316. };
  1317. var onPopupReady = function() {
  1318. var win = this.contentWindow;
  1319. if ( !win || win.location.host !== location.host ) {
  1320. return;
  1321. }
  1322. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1323. attributes: true,
  1324. characterData: true,
  1325. subtree: true
  1326. });
  1327. delayedResize();
  1328. };
  1329. iframe.addEventListener('load', onPopupReady, true);
  1330. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1331. .getInterface(Ci.nsIDOMWindowUtils)
  1332. .loadSheet(this.styleURI, 1);
  1333. };
  1334. /******************************************************************************/
  1335. vAPI.toolbarButton.onViewShowing = function({target}) {
  1336. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1337. };
  1338. /******************************************************************************/
  1339. vAPI.toolbarButton.onViewHiding = function({target}) {
  1340. target.parentNode.style.maxWidth = '';
  1341. target.firstChild.setAttribute('src', 'about:blank');
  1342. };
  1343. /******************************************************************************/
  1344. vAPI.toolbarButton.updateState = function(win, tabId) {
  1345. var button = win.document.getElementById(this.id);
  1346. if ( !button ) {
  1347. return;
  1348. }
  1349. var icon = this.tabs[tabId];
  1350. button.setAttribute('badge', icon && icon.badge || '');
  1351. var iconId = icon && icon.img ? icon.img : 'off';
  1352. icon = 'url(' + vAPI.getURL('img/browsericons/icon19-' + iconId + '.png') + ')';
  1353. button.style.listStyleImage = icon;
  1354. };
  1355. /******************************************************************************/
  1356. vAPI.toolbarButton.init();
  1357. /******************************************************************************/
  1358. /******************************************************************************/
  1359. vAPI.contextMenu = {
  1360. contextMap: {
  1361. frame: 'inFrame',
  1362. link: 'onLink',
  1363. image: 'onImage',
  1364. audio: 'onAudio',
  1365. video: 'onVideo',
  1366. editable: 'onEditableArea'
  1367. }
  1368. };
  1369. /******************************************************************************/
  1370. vAPI.contextMenu.displayMenuItem = function({target}) {
  1371. var doc = target.ownerDocument;
  1372. var gContextMenu = doc.defaultView.gContextMenu;
  1373. if ( !gContextMenu.browser ) {
  1374. return;
  1375. }
  1376. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1377. var currentURI = gContextMenu.browser.currentURI;
  1378. // https://github.com/chrisaljoudi/uBlock/issues/105
  1379. // TODO: Should the element picker works on any kind of pages?
  1380. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1381. menuitem.hidden = true;
  1382. return;
  1383. }
  1384. var ctx = vAPI.contextMenu.contexts;
  1385. if ( !ctx ) {
  1386. menuitem.hidden = false;
  1387. return;
  1388. }
  1389. var ctxMap = vAPI.contextMenu.contextMap;
  1390. for ( var context of ctx ) {
  1391. if (
  1392. context === 'page' &&
  1393. !gContextMenu.onLink &&
  1394. !gContextMenu.onImage &&
  1395. !gContextMenu.onEditableArea &&
  1396. !gContextMenu.inFrame &&
  1397. !gContextMenu.onVideo &&
  1398. !gContextMenu.onAudio
  1399. ) {
  1400. menuitem.hidden = false;
  1401. return;
  1402. }
  1403. if ( gContextMenu[ctxMap[context]] ) {
  1404. menuitem.hidden = false;
  1405. return;
  1406. }
  1407. }
  1408. menuitem.hidden = true;
  1409. };
  1410. /******************************************************************************/
  1411. vAPI.contextMenu.register = function(doc) {
  1412. if ( !this.menuItemId ) {
  1413. return;
  1414. }
  1415. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1416. var menuitem = doc.createElement('menuitem');
  1417. menuitem.setAttribute('id', this.menuItemId);
  1418. menuitem.setAttribute('label', this.menuLabel);
  1419. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon19-19.png'));
  1420. menuitem.setAttribute('class', 'menuitem-iconic');
  1421. menuitem.addEventListener('command', this.onCommand);
  1422. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1423. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1424. };
  1425. /******************************************************************************/
  1426. vAPI.contextMenu.unregister = function(doc) {
  1427. if ( !this.menuItemId ) {
  1428. return;
  1429. }
  1430. var menuitem = doc.getElementById(this.menuItemId);
  1431. var contextMenu = menuitem.parentNode;
  1432. menuitem.removeEventListener('command', this.onCommand);
  1433. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1434. contextMenu.removeChild(menuitem);
  1435. };
  1436. /******************************************************************************/
  1437. vAPI.contextMenu.create = function(details, callback) {
  1438. this.menuItemId = details.id;
  1439. this.menuLabel = details.title;
  1440. this.contexts = details.contexts;
  1441. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1442. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1443. } else {
  1444. // default in Chrome
  1445. this.contexts = ['page'];
  1446. }
  1447. this.onCommand = function() {
  1448. var gContextMenu = getOwnerWindow(this).gContextMenu;
  1449. var details = {
  1450. menuItemId: this.id
  1451. };
  1452. if ( gContextMenu.inFrame ) {
  1453. details.tagName = 'iframe';
  1454. // Probably won't work with e10s
  1455. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1456. } else if ( gContextMenu.onImage ) {
  1457. details.tagName = 'img';
  1458. details.srcUrl = gContextMenu.mediaURL;
  1459. } else if ( gContextMenu.onAudio ) {
  1460. details.tagName = 'audio';
  1461. details.srcUrl = gContextMenu.mediaURL;
  1462. } else if ( gContextMenu.onVideo ) {
  1463. details.tagName = 'video';
  1464. details.srcUrl = gContextMenu.mediaURL;
  1465. } else if ( gContextMenu.onLink ) {
  1466. details.tagName = 'a';
  1467. details.linkUrl = gContextMenu.linkURL;
  1468. }
  1469. callback(details, {
  1470. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1471. url: gContextMenu.browser.currentURI.asciiSpec
  1472. });
  1473. };
  1474. for ( var win of vAPI.tabs.getWindows() ) {
  1475. this.register(win.document);
  1476. }
  1477. };
  1478. /******************************************************************************/
  1479. vAPI.contextMenu.remove = function() {
  1480. for ( var win of vAPI.tabs.getWindows() ) {
  1481. this.unregister(win.document);
  1482. }
  1483. this.menuItemId = null;
  1484. this.menuLabel = null;
  1485. this.contexts = null;
  1486. this.onCommand = null;
  1487. };
  1488. /******************************************************************************/
  1489. /******************************************************************************/
  1490. var optionsObserver = {
  1491. addonId: 'uMatrix@raymondhill.net',
  1492. register: function() {
  1493. Services.obs.addObserver(this, 'addon-options-displayed', false);
  1494. cleanupTasks.push(this.unregister.bind(this));
  1495. var browser = getBrowserForTab(vAPI.tabs.get(null));
  1496. if ( browser && browser.currentURI && browser.currentURI.spec === 'about:addons' ) {
  1497. this.observe(browser.contentDocument, 'addon-enabled', this.addonId);
  1498. }
  1499. },
  1500. unregister: function() {
  1501. Services.obs.removeObserver(this, 'addon-options-displayed');
  1502. },
  1503. setupOptionsButton: function(doc, id, page) {
  1504. var button = doc.getElementById(id);
  1505. if ( button === null ) {
  1506. return;
  1507. }
  1508. button.addEventListener('command', function() {
  1509. vAPI.tabs.open({ url: page, index: -1 });
  1510. });
  1511. button.label = vAPI.i18n(id);
  1512. },
  1513. observe: function(doc, topic, addonId) {
  1514. if ( addonId !== this.addonId ) {
  1515. return;
  1516. }
  1517. this.setupOptionsButton(doc, 'showDashboardButton', 'dashboard.html');
  1518. this.setupOptionsButton(doc, 'showNetworkLogButton', 'devtools.html');
  1519. }
  1520. };
  1521. optionsObserver.register();
  1522. /******************************************************************************/
  1523. /******************************************************************************/
  1524. vAPI.lastError = function() {
  1525. return null;
  1526. };
  1527. /******************************************************************************/
  1528. /******************************************************************************/
  1529. // This is called only once, when everything has been loaded in memory after
  1530. // the extension was launched. It can be used to inject content scripts
  1531. // in already opened web pages, to remove whatever nuisance could make it to
  1532. // the web pages before uBlock was ready.
  1533. vAPI.onLoadAllCompleted = function() {
  1534. for ( var tab of this.tabs.getAllSync() ) {
  1535. // We're insterested in only the tabs that were already loaded
  1536. getBrowserForTab(tab).messageManager.sendAsyncMessage(
  1537. location.host + '-load-completed'
  1538. );
  1539. }
  1540. };
  1541. /******************************************************************************/
  1542. /******************************************************************************/
  1543. // Likelihood is that we do not have to punycode: given punycode overhead,
  1544. // it's faster to check and skip than do it unconditionally all the time.
  1545. var punycodeHostname = punycode.toASCII;
  1546. var isNotASCII = /[^\x21-\x7F]/;
  1547. vAPI.punycodeHostname = function(hostname) {
  1548. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1549. };
  1550. vAPI.punycodeURL = function(url) {
  1551. if ( isNotASCII.test(url) ) {
  1552. return Services.io.newURI(url, null, null).asciiSpec;
  1553. }
  1554. return url;
  1555. };
  1556. /******************************************************************************/
  1557. /******************************************************************************/
  1558. vAPI.browserData = {};
  1559. /******************************************************************************/
  1560. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICacheService
  1561. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICache
  1562. vAPI.browserData.clearCache = function(callback) {
  1563. // PURGE_DISK_DATA_ONLY:1
  1564. // PURGE_DISK_ALL:2
  1565. // PURGE_EVERYTHING:3
  1566. // However I verified that not argument does clear the cache data.
  1567. Services.cache2.clear();
  1568. if ( typeof callback === 'function' ) {
  1569. callback();
  1570. }
  1571. };
  1572. /******************************************************************************/
  1573. vAPI.browserData.clearOrigin = function(/* domain */) {
  1574. // TODO
  1575. };
  1576. /******************************************************************************/
  1577. /******************************************************************************/
  1578. // https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookie2
  1579. // https://developer.mozilla.org/en-US/docs/Observer_Notifications#Cookies
  1580. vAPI.cookies = {};
  1581. /******************************************************************************/
  1582. vAPI.cookies.CookieEntry = function(ffCookie) {
  1583. this.domain = ffCookie.host;
  1584. this.name = ffCookie.name;
  1585. this.path = ffCookie.path;
  1586. this.secure = ffCookie.isSecure === true;
  1587. this.session = ffCookie.expires === 0;
  1588. this.value = ffCookie.value;
  1589. };
  1590. /******************************************************************************/
  1591. vAPI.cookies.start = function() {
  1592. Services.obs.addObserver(this, 'cookie-changed', false);
  1593. cleanupTasks.push(this.stop.bind(this));
  1594. };
  1595. /******************************************************************************/
  1596. vAPI.cookies.stop = function() {
  1597. Services.obs.removeObserver(this, 'cookie-changed');
  1598. };
  1599. /******************************************************************************/
  1600. vAPI.cookies.observe = function(subject, topic, reason) {
  1601. if ( topic !== 'cookie-changed' ) {
  1602. return;
  1603. }
  1604. var handler = reason === 'deleted' ? this.onRemoved : this.onChanged;
  1605. if ( typeof handler !== 'function' ) {
  1606. return;
  1607. }
  1608. handler(new this.CookieEntry(subject.QueryInterface(Ci.nsICookie)));
  1609. };
  1610. /******************************************************************************/
  1611. // Meant and expected to be asynchronous.
  1612. vAPI.cookies.getAll = function(callback) {
  1613. if ( typeof callback !== 'function' ) {
  1614. return;
  1615. }
  1616. var onAsync = function() {
  1617. var out = [];
  1618. var enumerator = Services.cookies.enumerator;
  1619. while ( enumerator.hasMoreElements() ) {
  1620. out.push(new this.CookieEntry(enumerator.getNext().QueryInterface(Ci.nsICookie)));
  1621. }
  1622. callback(out);
  1623. };
  1624. setTimeout(onAsync.bind(this), 0);
  1625. };
  1626. /******************************************************************************/
  1627. vAPI.cookies.remove = function(details, callback) {
  1628. var uri = Services.io.newURI(details.url, null, null);
  1629. var cookies = Services.cookies;
  1630. cookies.remove(uri.asciiHost, details.name, uri.path, false);
  1631. cookies.remove( '.' + uri.asciiHost, details.name, uri.path, false);
  1632. if ( typeof callback === 'function' ) {
  1633. callback({
  1634. domain: uri.asciiHost,
  1635. name: details.name,
  1636. path: uri.path
  1637. });
  1638. }
  1639. };
  1640. /******************************************************************************/
  1641. /******************************************************************************/
  1642. })();
  1643. /******************************************************************************/