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.

1428 lines
41 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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/uBlock
  15. */
  16. // For background page
  17. /******************************************************************************/
  18. (function() {
  19. 'use strict';
  20. /******************************************************************************/
  21. const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
  22. Cu.import('resource://gre/modules/Services.jsm');
  23. /******************************************************************************/
  24. self.vAPI = self.vAPI || {};
  25. vAPI.firefox = true;
  26. /******************************************************************************/
  27. // TODO: read these data from somewhere...
  28. vAPI.app = {
  29. name: 'µBlock',
  30. version: '0.8.2.3'
  31. };
  32. /******************************************************************************/
  33. vAPI.app.restart = function() {
  34. // Listening in bootstrap.js
  35. Cc['@mozilla.org/childprocessmessagemanager;1']
  36. .getService(Ci.nsIMessageSender)
  37. .sendAsyncMessage(location.host + '-restart');
  38. };
  39. /******************************************************************************/
  40. // List of things that needs to be destroyed when disabling the extension
  41. // Only functions should be added to it
  42. vAPI.unload = [];
  43. /******************************************************************************/
  44. var SQLite = {
  45. open: function() {
  46. var path = Services.dirsvc.get('ProfD', Ci.nsIFile);
  47. path.append('extension-data');
  48. if ( !path.exists() ) {
  49. path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0774', 8));
  50. }
  51. if ( !path.isDirectory() ) {
  52. throw Error('Should be a directory...');
  53. }
  54. path.append(location.host + '.sqlite');
  55. this.db = Services.storage.openDatabase(path);
  56. this.db.executeSimpleSQL(
  57. 'CREATE TABLE IF NOT EXISTS settings' +
  58. '(name TEXT PRIMARY KEY NOT NULL, value TEXT);'
  59. );
  60. vAPI.unload.push(function() {
  61. // VACUUM somewhere else, instead on unload?
  62. SQLite.run('VACUUM');
  63. SQLite.db.asyncClose();
  64. });
  65. },
  66. run: function(query, values, callback) {
  67. if ( !this.db ) {
  68. this.open();
  69. }
  70. var result = {};
  71. query = this.db.createAsyncStatement(query);
  72. if ( Array.isArray(values) && values.length ) {
  73. var i = values.length;
  74. while ( i-- ) {
  75. query.bindByIndex(i, values[i]);
  76. }
  77. }
  78. query.executeAsync({
  79. handleResult: function(rows) {
  80. if ( !rows || typeof callback !== 'function' ) {
  81. return;
  82. }
  83. var row;
  84. while ( row = rows.getNextRow() ) {
  85. // we assume that there will be two columns, since we're
  86. // using it only for preferences
  87. result[row.getResultByIndex(0)] = row.getResultByIndex(1);
  88. }
  89. },
  90. handleCompletion: function(reason) {
  91. if ( typeof callback === 'function' && reason === 0 ) {
  92. callback(result);
  93. }
  94. },
  95. handleError: function(error) {
  96. console.error('SQLite error ', error.result, error.message);
  97. }
  98. });
  99. }
  100. };
  101. /******************************************************************************/
  102. vAPI.storage = {
  103. QUOTA_BYTES: 100 * 1024 * 1024,
  104. sqlWhere: function(col, params) {
  105. if ( params > 0 ) {
  106. params = Array(params + 1).join('?, ').slice(0, -2);
  107. return ' WHERE ' + col + ' IN (' + params + ')';
  108. }
  109. return '';
  110. },
  111. get: function(details, callback) {
  112. if ( typeof callback !== 'function' ) {
  113. return;
  114. }
  115. var values = [], defaults = false;
  116. if ( details !== null ) {
  117. if ( Array.isArray(details) ) {
  118. values = details;
  119. } else if ( typeof details === 'object' ) {
  120. defaults = true;
  121. values = Object.keys(details);
  122. } else {
  123. values = [details.toString()];
  124. }
  125. }
  126. SQLite.run(
  127. 'SELECT * FROM settings' + this.sqlWhere('name', values.length),
  128. values,
  129. function(result) {
  130. var key;
  131. for ( key in result ) {
  132. result[key] = JSON.parse(result[key]);
  133. }
  134. if ( defaults ) {
  135. for ( key in details ) {
  136. if ( result[key] === undefined ) {
  137. result[key] = details[key];
  138. }
  139. }
  140. }
  141. callback(result);
  142. }
  143. );
  144. },
  145. set: function(details, callback) {
  146. var key, values = [], placeholders = [];
  147. for ( key in details ) {
  148. values.push(key);
  149. values.push(JSON.stringify(details[key]));
  150. placeholders.push('?, ?');
  151. }
  152. if ( !values.length ) {
  153. return;
  154. }
  155. SQLite.run(
  156. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  157. placeholders.join(' UNION SELECT '),
  158. values,
  159. callback
  160. );
  161. },
  162. remove: function(keys, callback) {
  163. if ( typeof keys === 'string' ) {
  164. keys = [keys];
  165. }
  166. SQLite.run(
  167. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  168. keys,
  169. callback
  170. );
  171. },
  172. clear: function(callback) {
  173. SQLite.run('DELETE FROM settings');
  174. SQLite.run('VACUUM', null, callback);
  175. },
  176. getBytesInUse: function(keys, callback) {
  177. if ( typeof callback !== 'function' ) {
  178. return;
  179. }
  180. SQLite.run(
  181. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  182. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  183. keys,
  184. function(result) {
  185. callback(result.size);
  186. }
  187. );
  188. }
  189. };
  190. /******************************************************************************/
  191. var windowWatcher = {
  192. onTabClose: function(e) {
  193. var tabId = vAPI.tabs.getTabId(e.target);
  194. vAPI.tabs.onClosed(tabId);
  195. delete vAPI.tabIcons[tabId];
  196. },
  197. onTabSelect: function(e) {
  198. vAPI.setIcon(
  199. vAPI.tabs.getTabId(e.target),
  200. e.target.ownerDocument.defaultView
  201. );
  202. },
  203. onReady: function(e) {
  204. if ( e ) {
  205. this.removeEventListener(e.type, windowWatcher.onReady);
  206. }
  207. var wintype = this.document.documentElement.getAttribute('windowtype');
  208. if ( wintype !== 'navigator:browser' ) {
  209. return;
  210. }
  211. if ( !this.gBrowser || !this.gBrowser.tabContainer ) {
  212. return;
  213. }
  214. var tC = this.gBrowser.tabContainer;
  215. this.gBrowser.addTabsProgressListener(tabsProgressListener);
  216. tC.addEventListener('TabClose', windowWatcher.onTabClose);
  217. tC.addEventListener('TabSelect', windowWatcher.onTabSelect);
  218. vAPI.toolbarButton.register(this.document);
  219. vAPI.contextMenu.register(this.document);
  220. // when new window is opened TabSelect doesn't run on the selected tab?
  221. },
  222. observe: function(win, topic) {
  223. if ( topic === 'domwindowopened' ) {
  224. win.addEventListener('DOMContentLoaded', this.onReady);
  225. }
  226. }
  227. };
  228. /******************************************************************************/
  229. var tabsProgressListener = {
  230. onLocationChange: function(browser, webProgress, request, location, flags) {
  231. if ( !webProgress.isTopLevel ) {
  232. return;
  233. }
  234. var tabId = vAPI.tabs.getTabId(browser);
  235. if ( flags & 1 ) {
  236. vAPI.tabs.onUpdated(tabId, {url: location.spec}, {
  237. frameId: 0,
  238. tabId: tabId,
  239. url: browser.currentURI.spec
  240. });
  241. } else if ( location.scheme === 'http' || location.scheme === 'https' ) {
  242. vAPI.tabs.onNavigation({
  243. frameId: 0,
  244. tabId: tabId,
  245. url: location.spec
  246. });
  247. }
  248. }
  249. };
  250. /******************************************************************************/
  251. vAPI.tabs = {};
  252. /******************************************************************************/
  253. vAPI.tabs.registerListeners = function() {
  254. // onNavigation and onUpdated handled with tabsProgressListener
  255. // onClosed - handled in windowWatcher.onTabClose
  256. // onPopup ?
  257. for ( var win of this.getWindows() ) {
  258. windowWatcher.onReady.call(win);
  259. }
  260. Services.ww.registerNotification(windowWatcher);
  261. vAPI.toolbarButton.init();
  262. vAPI.unload.push(function() {
  263. Services.ww.unregisterNotification(windowWatcher);
  264. for ( var win of vAPI.tabs.getWindows() ) {
  265. vAPI.toolbarButton.unregister(win.document);
  266. vAPI.contextMenu.unregister(win.document);
  267. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  268. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  269. var tC = win.gBrowser.tabContainer;
  270. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  271. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  272. // close extension tabs
  273. for ( var tab of win.gBrowser.tabs ) {
  274. var URI = tab.linkedBrowser.currentURI;
  275. if ( URI.scheme === 'chrome' && URI.host === location.host ) {
  276. win.gBrowser.removeTab(tab);
  277. }
  278. }
  279. }
  280. });
  281. };
  282. /******************************************************************************/
  283. vAPI.tabs.getTabId = function(target) {
  284. if ( target.linkedPanel ) {
  285. return target.linkedPanel.slice(6);
  286. }
  287. var i, gBrowser = target.ownerDocument.defaultView.gBrowser;
  288. // This should be more efficient from version 35
  289. if ( gBrowser.getTabForBrowser ) {
  290. i = gBrowser.getTabForBrowser(target);
  291. return i ? i.linkedPanel.slice(6) : -1;
  292. }
  293. i = gBrowser.browsers.indexOf(target);
  294. if ( i !== -1 ) {
  295. i = gBrowser.tabs[i].linkedPanel.slice(6);
  296. }
  297. return i;
  298. };
  299. /******************************************************************************/
  300. vAPI.tabs.get = function(tabId, callback) {
  301. var tab, windows;
  302. if ( tabId === null ) {
  303. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  304. tabId = vAPI.tabs.getTabId(tab);
  305. } else {
  306. windows = this.getWindows();
  307. for ( var win of windows ) {
  308. tab = win.gBrowser.tabContainer.querySelector(
  309. 'tab[linkedpanel="panel-' + tabId + '"]'
  310. );
  311. if ( tab ) {
  312. break;
  313. }
  314. }
  315. }
  316. // for internal use
  317. if ( typeof callback !== 'function' ) {
  318. return tab;
  319. }
  320. if ( !tab ) {
  321. callback();
  322. return;
  323. }
  324. var browser = tab.linkedBrowser;
  325. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  326. if ( !windows ) {
  327. windows = this.getWindows();
  328. }
  329. callback({
  330. id: tabId,
  331. index: gBrowser.browsers.indexOf(browser),
  332. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  333. active: tab === gBrowser.selectedTab,
  334. url: browser.currentURI.spec,
  335. title: tab.label
  336. });
  337. };
  338. /******************************************************************************/
  339. vAPI.tabs.getAll = function(window) {
  340. var win, tab, tabs = [];
  341. for ( win of this.getWindows() ) {
  342. if ( window && window !== win ) {
  343. continue;
  344. }
  345. for ( tab of win.gBrowser.tabs ) {
  346. tabs.push(tab);
  347. }
  348. }
  349. return tabs;
  350. };
  351. /******************************************************************************/
  352. vAPI.tabs.getWindows = function() {
  353. var winumerator = Services.wm.getEnumerator('navigator:browser');
  354. var windows = [];
  355. while ( winumerator.hasMoreElements() ) {
  356. var win = winumerator.getNext();
  357. if ( !win.closed ) {
  358. windows.push(win);
  359. }
  360. }
  361. return windows;
  362. };
  363. /******************************************************************************/
  364. // properties of the details object:
  365. // url: 'URL', // the address that will be opened
  366. // tabId: 1, // the tab is used if set, instead of creating a new one
  367. // index: -1, // undefined: end of the list, -1: following tab, or after index
  368. // active: false, // opens the tab in background - true and undefined: foreground
  369. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  370. vAPI.tabs.open = function(details) {
  371. if ( !details.url ) {
  372. return null;
  373. }
  374. // extension pages
  375. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  376. details.url = vAPI.getURL(details.url);
  377. }
  378. var tab, tabs;
  379. if ( details.select ) {
  380. var rgxHash = /#.*/;
  381. // this is questionable
  382. var url = details.url.replace(rgxHash, '');
  383. tabs = this.getAll();
  384. for ( tab of tabs ) {
  385. var browser = tab.linkedBrowser;
  386. if ( browser.currentURI.spec.replace(rgxHash, '') === url ) {
  387. browser.ownerDocument.defaultView.gBrowser.selectedTab = tab;
  388. return;
  389. }
  390. }
  391. }
  392. if ( details.active === undefined ) {
  393. details.active = true;
  394. }
  395. var gBrowser = Services.wm.getMostRecentWindow('navigator:browser').gBrowser;
  396. if ( details.index === -1 ) {
  397. details.index = gBrowser.browsers.indexOf(gBrowser.selectedBrowser) + 1;
  398. }
  399. if ( details.tabId ) {
  400. tabs = tabs || this.getAll();
  401. for ( tab of tabs ) {
  402. if ( vAPI.tabs.getTabId(tab) === details.tabId ) {
  403. tab.linkedBrowser.loadURI(details.url);
  404. return;
  405. }
  406. }
  407. }
  408. tab = gBrowser.loadOneTab(details.url, {inBackground: !details.active});
  409. if ( details.index !== undefined ) {
  410. gBrowser.moveTabTo(tab, details.index);
  411. }
  412. };
  413. /******************************************************************************/
  414. vAPI.tabs.remove = function(tabIds) {
  415. if ( !Array.isArray(tabIds) ) {
  416. tabIds = [tabIds];
  417. }
  418. tabIds = tabIds.map(function(tabId) {
  419. return 'tab[linkedpanel="panel-' + tabId + '"]';
  420. }).join(',');
  421. for ( var win of this.getWindows() ) {
  422. var tabs = win.gBrowser.tabContainer.querySelectorAll(tabIds);
  423. if ( !tabs ) {
  424. continue;
  425. }
  426. for ( var tab of tabs ) {
  427. win.gBrowser.removeTab(tab);
  428. }
  429. }
  430. };
  431. /******************************************************************************/
  432. vAPI.tabs.reload = function(tabId) {
  433. var tab = this.get(tabId);
  434. if ( tab ) {
  435. tab.ownerDocument.defaultView.gBrowser.reloadTab(tab);
  436. }
  437. };
  438. /******************************************************************************/
  439. vAPI.tabs.injectScript = function(tabId, details, callback) {
  440. var tab = vAPI.tabs.get(tabId);
  441. if ( !tab ) {
  442. return;
  443. }
  444. if ( details.file ) {
  445. details.file = vAPI.getURL(details.file);
  446. }
  447. tab.linkedBrowser.messageManager.sendAsyncMessage(
  448. location.host + ':broadcast',
  449. JSON.stringify({
  450. broadcast: true,
  451. channelName: 'vAPI',
  452. msg: {
  453. cmd: 'injectScript',
  454. details: details
  455. }
  456. })
  457. );
  458. if ( typeof callback === 'function' ) {
  459. setTimeout(callback, 13);
  460. }
  461. };
  462. /******************************************************************************/
  463. vAPI.tabIcons = { /*tabId: {badge: 0, img: boolean}*/ };
  464. vAPI.setIcon = function(tabId, iconStatus, badge) {
  465. // If badge is undefined, then setIcon was called from the TabSelect event
  466. var curWin = badge === undefined
  467. ? iconStatus
  468. : Services.wm.getMostRecentWindow('navigator:browser');
  469. var curTabId = vAPI.tabs.getTabId(curWin.gBrowser.selectedTab);
  470. // from 'TabSelect' event
  471. if ( tabId === undefined ) {
  472. tabId = curTabId;
  473. } else if ( badge !== undefined ) {
  474. vAPI.tabIcons[tabId] = {
  475. badge: badge,
  476. img: iconStatus === 'on'
  477. };
  478. }
  479. if ( tabId !== curTabId ) {
  480. return;
  481. }
  482. var button = curWin.document.getElementById(vAPI.toolbarButton.widgetId);
  483. if ( !button ) {
  484. return;
  485. }
  486. /*if ( !button.classList.contains('badged-button') ) {
  487. button.classList.add('badged-button');
  488. }*/
  489. var icon = vAPI.tabIcons[tabId];
  490. button.setAttribute('badge', icon && icon.badge || '');
  491. iconStatus = !button.image || !icon || !icon.img ? '-off' : '';
  492. button.image = vAPI.getURL('img/browsericons/icon16' + iconStatus + '.svg');
  493. };
  494. /******************************************************************************/
  495. vAPI.toolbarButton = {
  496. widgetId: location.host + '-button',
  497. panelId: location.host + '-panel'
  498. };
  499. /******************************************************************************/
  500. vAPI.toolbarButton.init = function() {
  501. const {CustomizableUI} = Cu.import('resource:///modules/CustomizableUI.jsm', {});
  502. CustomizableUI.createWidget({
  503. id: this.widgetId,
  504. type: 'view',
  505. viewId: this.panelId,
  506. defaultArea: CustomizableUI.AREA_NAVBAR,
  507. label: vAPI.app.name,
  508. tooltiptext: vAPI.app.name,
  509. onViewShowing: function({target}) {
  510. var hash = CustomizableUI.getWidget(vAPI.toolbarButton.widgetId)
  511. .areaType === CustomizableUI.TYPE_TOOLBAR ? '' : '#body';
  512. target.firstChild.setAttribute(
  513. 'src',
  514. vAPI.getURL('popup.html' + hash)
  515. );
  516. },
  517. onViewHiding: function({target}) {
  518. target.firstChild.setAttribute('src', 'about:blank');
  519. }
  520. });
  521. this.closePopup = function({target}) {
  522. CustomizableUI.hidePanelForNode(
  523. target.ownerDocument.getElementById(vAPI.toolbarButton.panelId)
  524. );
  525. };
  526. vAPI.messaging.globalMessageManager.addMessageListener(
  527. location.host + ':closePopup',
  528. this.closePopup
  529. );
  530. vAPI.unload.push(function() {
  531. CustomizableUI.destroyWidget(vAPI.toolbarButton.widgetId);
  532. vAPI.messaging.globalMessageManager.removeMessageListener(
  533. location.host + ':closePopup',
  534. vAPI.toolbarButton.closePopup
  535. );
  536. });
  537. };
  538. /******************************************************************************/
  539. // it runs with windowWatcher when a window is opened
  540. // vAPI.tabs.registerListeners initializes it
  541. vAPI.toolbarButton.register = function(doc) {
  542. var panel = doc.createElement('panelview');
  543. panel.setAttribute('id', this.panelId);
  544. var iframe = doc.createElement('iframe');
  545. iframe.setAttribute('type', 'content');
  546. doc.getElementById('PanelUI-multiView')
  547. .appendChild(panel)
  548. .appendChild(iframe);
  549. var updateTimer = null;
  550. var delayedResize = function() {
  551. if ( updateTimer ) {
  552. return;
  553. }
  554. updateTimer = setTimeout(resizePopup, 20);
  555. };
  556. var resizePopup = function() {
  557. var panelStyle = panel.style;
  558. var body = iframe.contentDocument.body;
  559. panelStyle.width = iframe.style.width = body.clientWidth + 'px';
  560. panelStyle.height = iframe.style.height = body.clientHeight + 'px';
  561. updateTimer = null;
  562. };
  563. var onPopupReady = function() {
  564. var win = this.contentWindow;
  565. if ( !win || win.location.host !== location.host ) {
  566. return;
  567. }
  568. new win.MutationObserver(delayedResize).observe(win.document, {
  569. childList: true,
  570. attributes: true,
  571. characterData: true,
  572. subtree: true
  573. });
  574. delayedResize();
  575. };
  576. iframe.addEventListener('load', onPopupReady, true);
  577. if ( !this.styleURI ) {
  578. this.styleURI = 'data:text/css,' + encodeURIComponent([
  579. '#' + this.widgetId + ' {',
  580. 'list-style-image: url(',
  581. vAPI.getURL('img/browsericons/icon16-off.svg'),
  582. ');',
  583. '}',
  584. '#' + this.widgetId + '[badge]:not([badge=""])::after {',
  585. 'position: absolute;',
  586. 'margin-left: -16px;',
  587. 'margin-top: 3px;',
  588. 'padding: 1px 2px;',
  589. 'font-size: 9px;',
  590. 'font-weight: bold;',
  591. 'color: #fff;',
  592. 'background: #666;',
  593. 'content: attr(badge);',
  594. '}',
  595. '#' + this.panelId + ', #' + this.panelId + ' > iframe {',
  596. 'width: 180px;',
  597. 'height: 310px;',
  598. 'overflow: hidden !important;',
  599. '}'
  600. ].join(''));
  601. this.styleURI = Services.io.newURI(this.styleURI, null, null);
  602. }
  603. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  604. getInterface(Ci.nsIDOMWindowUtils).loadSheet(this.styleURI, 1);
  605. };
  606. /******************************************************************************/
  607. vAPI.toolbarButton.unregister = function(doc) {
  608. var panel = doc.getElementById(this.panelId);
  609. panel.parentNode.removeChild(panel);
  610. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor).
  611. getInterface(Ci.nsIDOMWindowUtils).removeSheet(this.styleURI, 1);
  612. };
  613. /******************************************************************************/
  614. vAPI.messaging = {
  615. get globalMessageManager() {
  616. return Cc['@mozilla.org/globalmessagemanager;1']
  617. .getService(Ci.nsIMessageListenerManager);
  618. },
  619. frameScript: vAPI.getURL('frameScript.js'),
  620. listeners: {},
  621. defaultHandler: null,
  622. NOOPFUNC: function(){},
  623. UNHANDLED: 'vAPI.messaging.notHandled'
  624. };
  625. /******************************************************************************/
  626. vAPI.messaging.listen = function(listenerName, callback) {
  627. this.listeners[listenerName] = callback;
  628. };
  629. /******************************************************************************/
  630. vAPI.messaging.onMessage = function({target, data}) {
  631. var messageManager = target.messageManager;
  632. if ( !messageManager ) {
  633. // Message came from a popup, and its message manager is not usable.
  634. // So instead we broadcast to the parent window.
  635. messageManager = target
  636. .webNavigation.QueryInterface(Ci.nsIDocShell)
  637. .chromeEventHandler.ownerDocument.defaultView.messageManager;
  638. }
  639. var listenerId = data.channelName.split('|');
  640. var requestId = data.requestId;
  641. var channelName = listenerId[1];
  642. listenerId = listenerId[0];
  643. var callback = vAPI.messaging.NOOPFUNC;
  644. if ( requestId !== undefined ) {
  645. callback = function(response) {
  646. var message = JSON.stringify({
  647. requestId: requestId,
  648. channelName: channelName,
  649. msg: response !== undefined ? response : null
  650. });
  651. if ( messageManager.sendAsyncMessage ) {
  652. messageManager.sendAsyncMessage(listenerId, message);
  653. } else {
  654. messageManager.broadcastAsyncMessage(listenerId, message);
  655. }
  656. };
  657. }
  658. var sender = {
  659. tab: {
  660. id: vAPI.tabs.getTabId(target)
  661. }
  662. };
  663. // Specific handler
  664. var r = vAPI.messaging.UNHANDLED;
  665. var listener = vAPI.messaging.listeners[channelName];
  666. if ( typeof listener === 'function' ) {
  667. r = listener(data.msg, sender, callback);
  668. }
  669. if ( r !== vAPI.messaging.UNHANDLED ) {
  670. return;
  671. }
  672. // Default handler
  673. r = vAPI.messaging.defaultHandler(data.msg, sender, callback);
  674. if ( r !== vAPI.messaging.UNHANDLED ) {
  675. return;
  676. }
  677. console.error('µBlock> messaging > unknown request: %o', data);
  678. // Unhandled:
  679. // Need to callback anyways in case caller expected an answer, or
  680. // else there is a memory leak on caller's side
  681. callback();
  682. };
  683. /******************************************************************************/
  684. vAPI.messaging.setup = function(defaultHandler) {
  685. // Already setup?
  686. if ( this.defaultHandler !== null ) {
  687. return;
  688. }
  689. if ( typeof defaultHandler !== 'function' ) {
  690. defaultHandler = function(){ return vAPI.messaging.UNHANDLED; };
  691. }
  692. this.defaultHandler = defaultHandler;
  693. this.globalMessageManager.addMessageListener(
  694. location.host + ':background',
  695. this.onMessage
  696. );
  697. this.globalMessageManager.loadFrameScript(this.frameScript, true);
  698. vAPI.unload.push(function() {
  699. var gmm = vAPI.messaging.globalMessageManager;
  700. gmm.removeDelayedFrameScript(vAPI.messaging.frameScript);
  701. gmm.removeMessageListener(
  702. location.host + ':background',
  703. vAPI.messaging.onMessage
  704. );
  705. });
  706. };
  707. /******************************************************************************/
  708. vAPI.messaging.broadcast = function(message) {
  709. this.globalMessageManager.broadcastAsyncMessage(
  710. location.host + ':broadcast',
  711. JSON.stringify({broadcast: true, msg: message})
  712. );
  713. };
  714. /******************************************************************************/
  715. var httpObserver = {
  716. classDescription: 'net-channel-event-sinks for ' + location.host,
  717. classID: Components.ID('{dc8d6319-5f6e-4438-999e-53722db99e84}'),
  718. contractID: '@' + location.host + '/net-channel-event-sinks;1',
  719. ABORT: Components.results.NS_BINDING_ABORTED,
  720. ACCEPT: Components.results.NS_SUCCEEDED,
  721. MAIN_FRAME: Ci.nsIContentPolicy.TYPE_DOCUMENT,
  722. typeMap: {
  723. 2: 'script',
  724. 3: 'image',
  725. 4: 'stylesheet',
  726. 5: 'object',
  727. 6: 'main_frame',
  728. 7: 'sub_frame',
  729. 11: 'xmlhttprequest'
  730. },
  731. lastRequest: {
  732. url: null,
  733. type: null,
  734. tabId: null,
  735. frameId: null,
  736. parentFrameId: null,
  737. opener: null
  738. },
  739. get componentRegistrar() {
  740. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  741. },
  742. get categoryManager() {
  743. return Cc['@mozilla.org/categorymanager;1']
  744. .getService(Ci.nsICategoryManager);
  745. },
  746. QueryInterface: (function() {
  747. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', {});
  748. return XPCOMUtils.generateQI([
  749. Ci.nsIFactory,
  750. Ci.nsIObserver,
  751. Ci.nsIChannelEventSink,
  752. Ci.nsISupportsWeakReference
  753. ]);
  754. })(),
  755. createInstance: function(outer, iid) {
  756. if ( outer ) {
  757. throw Components.results.NS_ERROR_NO_AGGREGATION;
  758. }
  759. return this.QueryInterface(iid);
  760. },
  761. register: function() {
  762. Services.obs.addObserver(this, 'http-on-opening-request', true);
  763. Services.obs.addObserver(this, 'http-on-examine-response', true);
  764. this.componentRegistrar.registerFactory(
  765. this.classID,
  766. this.classDescription,
  767. this.contractID,
  768. this
  769. );
  770. this.categoryManager.addCategoryEntry(
  771. 'net-channel-event-sinks',
  772. this.contractID,
  773. this.contractID,
  774. false,
  775. true
  776. );
  777. },
  778. unregister: function() {
  779. Services.obs.removeObserver(this, 'http-on-opening-request');
  780. Services.obs.removeObserver(this, 'http-on-examine-response');
  781. this.componentRegistrar.unregisterFactory(this.classID, this);
  782. this.categoryManager.deleteCategoryEntry(
  783. 'net-channel-event-sinks',
  784. this.contractID,
  785. false
  786. );
  787. },
  788. handlePopup: function(URI, tabId, sourceTabId) {
  789. if ( !sourceTabId ) {
  790. return false;
  791. }
  792. if ( URI.scheme !== 'http' && URI.scheme !== 'https' ) {
  793. return false;
  794. }
  795. var result = vAPI.tabs.onPopup({
  796. tabId: tabId,
  797. sourceTabId: sourceTabId,
  798. url: URI.spec
  799. });
  800. return result === true;
  801. },
  802. handleRequest: function(channel, details) {
  803. var onBeforeRequest = vAPI.net.onBeforeRequest;
  804. var type = this.typeMap[details.type] || 'other';
  805. if ( onBeforeRequest.types.has(type) === false ) {
  806. return false;
  807. }
  808. var result = onBeforeRequest.callback({
  809. url: channel.URI.spec,
  810. type: type,
  811. tabId: details.tabId,
  812. frameId: details.frameId,
  813. parentFrameId: details.parentFrameId
  814. });
  815. if ( !result || typeof result !== 'object' ) {
  816. return false;
  817. }
  818. if ( result.cancel === true ) {
  819. channel.cancel(this.ABORT);
  820. return true;
  821. } else if ( result.redirectUrl ) {
  822. channel.redirectionLimit = 1;
  823. channel.redirectTo(
  824. Services.io.newURI(result.redirectUrl, null, null)
  825. );
  826. return true;
  827. }
  828. return false;
  829. },
  830. observe: function(channel, topic) {
  831. if ( !(channel instanceof Ci.nsIHttpChannel) ) {
  832. return;
  833. }
  834. var URI = channel.URI;
  835. var channelData, result;
  836. if ( topic === 'http-on-examine-response' ) {
  837. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  838. return;
  839. }
  840. try {
  841. // [tabId, type, sourceTabId - given if it was a popup]
  842. channelData = channel.getProperty(location.host + 'reqdata');
  843. } catch (ex) {
  844. return;
  845. }
  846. if ( !channelData || channelData[0] !== this.MAIN_FRAME ) {
  847. return;
  848. }
  849. topic = 'Content-Security-Policy';
  850. try {
  851. result = channel.getResponseHeader(topic);
  852. } catch (ex) {
  853. result = null;
  854. }
  855. result = vAPI.net.onHeadersReceived.callback({
  856. url: URI.spec,
  857. tabId: channelData[1],
  858. parentFrameId: -1,
  859. responseHeaders: result ? [{name: topic, value: result}] : []
  860. });
  861. if ( result ) {
  862. channel.setResponseHeader(
  863. topic,
  864. result.responseHeaders.pop().value,
  865. true
  866. );
  867. }
  868. return;
  869. }
  870. // http-on-opening-request
  871. var lastRequest = this.lastRequest;
  872. if ( !lastRequest.url || lastRequest.url !== URI.spec ) {
  873. lastRequest.url = null;
  874. return;
  875. }
  876. // Important! When loading file via XHR for mirroring,
  877. // the URL will be the same, so it could fall into an infinite loop
  878. lastRequest.url = null;
  879. var sourceTabId = null;
  880. // popup candidate (only for main_frame type)
  881. if ( lastRequest.opener ) {
  882. for ( var tab of vAPI.tabs.getAll() ) {
  883. var tabURI = tab.linkedBrowser.currentURI;
  884. // not the best approach
  885. if ( tabURI.spec === this.lastRequest.opener ) {
  886. sourceTabId = vAPI.tabs.getTabId(tab);
  887. break;
  888. }
  889. }
  890. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  891. channel.cancel(this.ABORT);
  892. return;
  893. }
  894. }
  895. if ( this.handleRequest(channel, lastRequest) ) {
  896. return;
  897. }
  898. // if request is not handled we may use the data in on-modify-request
  899. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  900. channel.setProperty(
  901. location.host + 'reqdata',
  902. [lastRequest.type, lastRequest.tabId, sourceTabId]
  903. );
  904. }
  905. },
  906. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  907. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  908. var result = this.ACCEPT;
  909. // If error thrown, the redirect will fail
  910. try {
  911. // skip internal redirects?
  912. /*if ( flags & 4 ) {
  913. console.log('internal redirect skipped');
  914. return;
  915. }*/
  916. var scheme = newChannel.URI.scheme;
  917. if ( scheme !== 'http' && scheme !== 'https' ) {
  918. return;
  919. }
  920. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  921. return;
  922. }
  923. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  924. var [type, tabId, sourceTabId] = channelData;
  925. if ( this.handlePopup(newChannel.URI, tabId, sourceTabId) ) {
  926. result = this.ABORT;
  927. return;
  928. }
  929. var details = {
  930. type: type,
  931. tabId: tabId,
  932. // well...
  933. frameId: type === this.MAIN_FRAME ? -1 : 0,
  934. parentFrameId: -1
  935. };
  936. if ( this.handleRequest(newChannel, details) ) {
  937. result = this.ABORT;
  938. return;
  939. }
  940. // carry the data on in case of multiple redirects
  941. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  942. newChannel.setProperty(location.host + 'reqdata', channelData);
  943. }
  944. } catch (ex) {
  945. // console.error(ex);
  946. } finally {
  947. callback.onRedirectVerifyCallback(result);
  948. }
  949. }
  950. };
  951. /******************************************************************************/
  952. vAPI.net = {};
  953. /******************************************************************************/
  954. vAPI.net.registerListeners = function() {
  955. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  956. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  957. var shouldLoadListener = function(e) {
  958. var details = e.data;
  959. // data: and about:blank
  960. if ( details.url.charAt(0) !== 'h' ) {
  961. vAPI.net.onBeforeRequest.callback({
  962. url: 'http://' + details.url.slice(0, details.url.indexOf(':')),
  963. type: 'main_frame',
  964. tabId: vAPI.tabs.getTabId(e.target),
  965. frameId: details.frameId,
  966. parentFrameId: details.parentFrameId
  967. });
  968. return;
  969. }
  970. var lastRequest = httpObserver.lastRequest;
  971. lastRequest.url = details.url;
  972. lastRequest.type = details.type;
  973. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  974. lastRequest.frameId = details.frameId;
  975. lastRequest.parentFrameId = details.parentFrameId;
  976. lastRequest.opener = details.opener;
  977. };
  978. vAPI.messaging.globalMessageManager.addMessageListener(
  979. shouldLoadListenerMessageName,
  980. shouldLoadListener
  981. );
  982. httpObserver.register();
  983. vAPI.unload.push(function() {
  984. vAPI.messaging.globalMessageManager.removeMessageListener(
  985. shouldLoadListenerMessageName,
  986. shouldLoadListener
  987. );
  988. httpObserver.unregister();
  989. });
  990. };
  991. /******************************************************************************/
  992. vAPI.contextMenu = {
  993. contextMap: {
  994. frame: 'inFrame',
  995. link: 'onLink',
  996. image: 'onImage',
  997. audio: 'onAudio',
  998. video: 'onVideo',
  999. editable: 'onEditableArea'
  1000. }
  1001. };
  1002. /******************************************************************************/
  1003. vAPI.contextMenu.displayMenuItem = function(e) {
  1004. var doc = e.target.ownerDocument;
  1005. var gContextMenu = doc.defaultView.gContextMenu;
  1006. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1007. if ( /^https?$/.test(gContextMenu.browser.currentURI.scheme) === false) {
  1008. menuitem.hidden = true;
  1009. return;
  1010. }
  1011. var ctx = vAPI.contextMenu.contexts;
  1012. if ( !ctx ) {
  1013. menuitem.hidden = false;
  1014. return;
  1015. }
  1016. var ctxMap = vAPI.contextMenu.contextMap;
  1017. for ( var context of ctx ) {
  1018. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1019. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1020. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1021. menuitem.hidden = false;
  1022. return;
  1023. }
  1024. if ( gContextMenu[ctxMap[context]] ) {
  1025. menuitem.hidden = false;
  1026. return;
  1027. }
  1028. }
  1029. menuitem.hidden = true;
  1030. };
  1031. /******************************************************************************/
  1032. vAPI.contextMenu.register = function(doc) {
  1033. if ( !this.menuItemId ) {
  1034. return;
  1035. }
  1036. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1037. var menuitem = doc.createElement('menuitem');
  1038. menuitem.setAttribute('id', this.menuItemId);
  1039. menuitem.setAttribute('label', this.menuLabel);
  1040. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1041. menuitem.setAttribute('class', 'menuitem-iconic');
  1042. menuitem.addEventListener('command', this.onCommand);
  1043. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1044. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1045. };
  1046. /******************************************************************************/
  1047. vAPI.contextMenu.unregister = function(doc) {
  1048. if ( !this.menuItemId ) {
  1049. return;
  1050. }
  1051. var menuitem = doc.getElementById(this.menuItemId);
  1052. var contextMenu = menuitem.parentNode;
  1053. menuitem.removeEventListener('command', this.onCommand);
  1054. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1055. contextMenu.removeChild(menuitem);
  1056. };
  1057. /******************************************************************************/
  1058. vAPI.contextMenu.create = function(details, callback) {
  1059. this.menuItemId = details.id;
  1060. this.menuLabel = details.title;
  1061. this.contexts = details.contexts;
  1062. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1063. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1064. } else {
  1065. // default in Chrome
  1066. this.contexts = ['page'];
  1067. }
  1068. this.onCommand = function() {
  1069. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1070. var details = {
  1071. menuItemId: this.id,
  1072. tagName: gContextMenu.target.tagName.toLowerCase()
  1073. };
  1074. if ( gContextMenu.inFrame ) {
  1075. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1076. } else if ( gContextMenu.onImage || gContextMenu.onAudio || gContextMenu.onVideo ) {
  1077. details.srcUrl = gContextMenu.mediaURL;
  1078. } else if ( gContextMenu.onLink ) {
  1079. details.linkUrl = gContextMenu.linkURL;
  1080. }
  1081. callback(details, {
  1082. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1083. url: gContextMenu.browser.currentURI.spec
  1084. });
  1085. };
  1086. for ( var win of vAPI.tabs.getWindows() ) {
  1087. this.register(win.document);
  1088. }
  1089. };
  1090. /******************************************************************************/
  1091. vAPI.contextMenu.remove = function() {
  1092. for ( var win of vAPI.tabs.getWindows() ) {
  1093. this.unregister(win.document);
  1094. }
  1095. this.menuItemId = null;
  1096. this.menuLabel = null;
  1097. this.contexts = null;
  1098. this.onCommand = null;
  1099. };
  1100. /******************************************************************************/
  1101. vAPI.lastError = function() {
  1102. return null;
  1103. };
  1104. /******************************************************************************/
  1105. // This is called only once, when everything has been loaded in memory after
  1106. // the extension was launched. It can be used to inject content scripts
  1107. // in already opened web pages, to remove whatever nuisance could make it to
  1108. // the web pages before uBlock was ready.
  1109. vAPI.onLoadAllCompleted = function() {};
  1110. /******************************************************************************/
  1111. // clean up when the extension is disabled
  1112. window.addEventListener('unload', function() {
  1113. for ( var unload of vAPI.unload ) {
  1114. unload();
  1115. }
  1116. // frameModule needs to be cleared too
  1117. var frameModule = {};
  1118. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1119. frameModule.contentObserver.unregister();
  1120. Cu.unload(vAPI.getURL('frameModule.js'));
  1121. });
  1122. /******************************************************************************/
  1123. })();
  1124. /******************************************************************************/