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.

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