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.

1566 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. /*[
  754. type,
  755. tabId,
  756. sourceTabId - given if it was a popup,
  757. frameId,
  758. parentFrameId
  759. ]*/
  760. channelData = channel.getProperty(location.host + 'reqdata');
  761. } catch (ex) {
  762. return;
  763. }
  764. if ( !channelData ) {
  765. return;
  766. }
  767. if ( (1 << channelData[0] & this.VALID_CSP_TARGETS) === 0 ) {
  768. return;
  769. }
  770. topic = 'Content-Security-Policy';
  771. try {
  772. result = channel.getResponseHeader(topic);
  773. } catch (ex) {
  774. result = null;
  775. }
  776. result = vAPI.net.onHeadersReceived.callback({
  777. hostname: URI.asciiHost,
  778. parentFrameId: channelData[4],
  779. responseHeaders: result ? [{name: topic, value: result}] : [],
  780. tabId: channelData[1],
  781. url: URI.asciiSpec
  782. });
  783. if ( result ) {
  784. channel.setResponseHeader(
  785. topic,
  786. result.responseHeaders.pop().value,
  787. true
  788. );
  789. }
  790. return;
  791. }
  792. // http-on-opening-request
  793. var lastRequest = this.lastRequest;
  794. if ( lastRequest.url === null ) {
  795. this.handleRequest(channel, URI, {tabId: vAPI.noTabId, type: 1});
  796. return;
  797. }
  798. // Important! When loading file via XHR for mirroring,
  799. // the URL will be the same, so it could fall into an infinite loop
  800. lastRequest.url = null;
  801. var sourceTabId = null;
  802. // Popup candidate (only for main_frame type)
  803. if ( lastRequest.openerURL ) {
  804. for ( var tab of vAPI.tabs.getAll() ) {
  805. var tabURI = tab.linkedBrowser.currentURI;
  806. // Probably isn't the best method to identify the source tab
  807. if ( tabURI.spec !== lastRequest.openerURL ) {
  808. continue;
  809. }
  810. sourceTabId = vAPI.tabs.getTabId(tab);
  811. if ( sourceTabId !== lastRequest.tabId ) {
  812. break;
  813. }
  814. sourceTabId = null;
  815. }
  816. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  817. channel.cancel(this.ABORT);
  818. return;
  819. }
  820. }
  821. if ( this.handleRequest(channel, URI, lastRequest) ) {
  822. return;
  823. }
  824. // If request is not handled we may use the data in on-modify-request
  825. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  826. channel.setProperty(
  827. location.host + 'reqdata',
  828. [
  829. lastRequest.type,
  830. lastRequest.tabId,
  831. sourceTabId,
  832. lastRequest.frameId,
  833. lastRequest.parentFrameId
  834. ]
  835. );
  836. }
  837. },
  838. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  839. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  840. var result = this.ACCEPT;
  841. // If error thrown, the redirect will fail
  842. try {
  843. // skip internal redirects?
  844. /*if ( flags & 4 ) {
  845. console.log('internal redirect skipped');
  846. return;
  847. }*/
  848. var URI = newChannel.URI;
  849. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  850. return;
  851. }
  852. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  853. return;
  854. }
  855. // TODO: what if a behind-the-scene request is being redirected?
  856. // This data is present only for tabbed requests, so if this throws,
  857. // the redirection won't be evaluated and canceled (if necessary)
  858. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  859. if ( this.handlePopup(URI, channelData[1], channelData[2]) ) {
  860. result = this.ABORT;
  861. return;
  862. }
  863. var details = {
  864. type: channelData[0],
  865. tabId: channelData[1],
  866. frameId: channelData[3],
  867. parentFrameId: channelData[4]
  868. };
  869. if ( this.handleRequest(newChannel, URI, details) ) {
  870. result = this.ABORT;
  871. return;
  872. }
  873. // Carry the data on in case of multiple redirects
  874. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  875. newChannel.setProperty(location.host + 'reqdata', channelData);
  876. }
  877. } catch (ex) {
  878. // console.error(ex);
  879. } finally {
  880. callback.onRedirectVerifyCallback(result);
  881. }
  882. }
  883. };
  884. /******************************************************************************/
  885. vAPI.net = {};
  886. /******************************************************************************/
  887. vAPI.net.registerListeners = function() {
  888. // Since it's not used
  889. this.onBeforeSendHeaders = null;
  890. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  891. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  892. var shouldLoadListener = function(e) {
  893. var details = e.data;
  894. var lastRequest = httpObserver.lastRequest;
  895. lastRequest.url = details.url;
  896. lastRequest.type = details.type;
  897. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  898. lastRequest.frameId = details.frameId;
  899. lastRequest.parentFrameId = details.parentFrameId;
  900. lastRequest.openerURL = details.openerURL;
  901. };
  902. vAPI.messaging.globalMessageManager.addMessageListener(
  903. shouldLoadListenerMessageName,
  904. shouldLoadListener
  905. );
  906. httpObserver.register();
  907. cleanupTasks.push(function() {
  908. vAPI.messaging.globalMessageManager.removeMessageListener(
  909. shouldLoadListenerMessageName,
  910. shouldLoadListener
  911. );
  912. httpObserver.unregister();
  913. });
  914. };
  915. /******************************************************************************/
  916. vAPI.toolbarButton = {
  917. id: location.host + '-button',
  918. type: 'view',
  919. viewId: location.host + '-panel',
  920. label: vAPI.app.name,
  921. tooltiptext: vAPI.app.name,
  922. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  923. };
  924. /******************************************************************************/
  925. vAPI.toolbarButton.init = function() {
  926. try {
  927. var {CustomizableUI} = Cu.import('resource:///modules/CustomizableUI.jsm', null);
  928. } catch (ex) {
  929. return;
  930. }
  931. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  932. this.styleURI = [
  933. '#' + this.id + ' {',
  934. 'list-style-image: url(',
  935. vAPI.getURL('img/browsericons/icon16-off.svg'),
  936. ');',
  937. '}',
  938. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  939. 'width: 160px;',
  940. 'height: 290px;',
  941. 'overflow: hidden !important;',
  942. '}'
  943. ];
  944. var platformVersion = Services.appinfo.platformVersion;
  945. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  946. this.styleURI.push(
  947. '#' + this.id + '[badge]:not([badge=""])::after {',
  948. 'position: absolute;',
  949. 'margin-left: -16px;',
  950. 'margin-top: 3px;',
  951. 'padding: 1px 2px;',
  952. 'font-size: 9px;',
  953. 'font-weight: bold;',
  954. 'color: #fff;',
  955. 'background: #666;',
  956. 'content: attr(badge);',
  957. '}'
  958. );
  959. }
  960. this.styleURI = Services.io.newURI(
  961. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  962. null,
  963. null
  964. );
  965. this.closePopup = function({target}) {
  966. CustomizableUI.hidePanelForNode(
  967. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  968. );
  969. };
  970. CustomizableUI.createWidget(this);
  971. vAPI.messaging.globalMessageManager.addMessageListener(
  972. location.host + ':closePopup',
  973. this.closePopup
  974. );
  975. cleanupTasks.push(function() {
  976. CustomizableUI.destroyWidget(this.id);
  977. vAPI.messaging.globalMessageManager.removeMessageListener(
  978. location.host + ':closePopup',
  979. this.closePopup
  980. );
  981. for ( var win of vAPI.tabs.getWindows() ) {
  982. var panel = win.document.getElementById(this.viewId);
  983. panel.parentNode.removeChild(panel);
  984. win.QueryInterface(Ci.nsIInterfaceRequestor)
  985. .getInterface(Ci.nsIDOMWindowUtils)
  986. .removeSheet(this.styleURI, 1);
  987. }
  988. }.bind(this));
  989. };
  990. /******************************************************************************/
  991. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  992. var panel = doc.createElement('panelview');
  993. panel.setAttribute('id', this.viewId);
  994. var iframe = doc.createElement('iframe');
  995. iframe.setAttribute('type', 'content');
  996. doc.getElementById('PanelUI-multiView')
  997. .appendChild(panel)
  998. .appendChild(iframe);
  999. var updateTimer = null;
  1000. var delayedResize = function() {
  1001. if ( updateTimer ) {
  1002. return;
  1003. }
  1004. updateTimer = setTimeout(resizePopup, 20);
  1005. };
  1006. var resizePopup = function() {
  1007. var body = iframe.contentDocument.body;
  1008. panel.parentNode.style.maxWidth = 'none';
  1009. // Set the hegiht first, then the width for proper resising
  1010. panel.style.height = iframe.style.height = body.clientHeight + 'px';
  1011. panel.style.width = iframe.style.width = body.clientWidth + 'px';
  1012. updateTimer = null;
  1013. };
  1014. var onPopupReady = function() {
  1015. var win = this.contentWindow;
  1016. if ( !win || win.location.host !== location.host ) {
  1017. return;
  1018. }
  1019. new win.MutationObserver(delayedResize).observe(win.document.body, {
  1020. attributes: true,
  1021. characterData: true,
  1022. subtree: true
  1023. });
  1024. delayedResize();
  1025. };
  1026. iframe.addEventListener('load', onPopupReady, true);
  1027. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  1028. .getInterface(Ci.nsIDOMWindowUtils)
  1029. .loadSheet(this.styleURI, 1);
  1030. };
  1031. /******************************************************************************/
  1032. vAPI.toolbarButton.onCreated = function(button) {
  1033. var platformVersion = Services.appinfo.platformVersion;
  1034. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1035. return;
  1036. }
  1037. button.setAttribute('badge', '');
  1038. button.classList.add('badged-button');
  1039. setTimeout(function() {
  1040. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1041. button,
  1042. 'class',
  1043. 'toolbarbutton-badge'
  1044. );
  1045. if ( !badge ) {
  1046. return;
  1047. }
  1048. badge.style.cssText = [
  1049. 'position: absolute;',
  1050. 'bottom: 0;',
  1051. 'right: 0;',
  1052. 'padding: 1px;',
  1053. 'background: #666;',
  1054. 'color: #fff;',
  1055. 'font-size: 9px;',
  1056. 'font-weight: bold;'
  1057. ].join('');
  1058. }, 1000);
  1059. };
  1060. /******************************************************************************/
  1061. vAPI.toolbarButton.onViewShowing = function({target}) {
  1062. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1063. };
  1064. /******************************************************************************/
  1065. vAPI.toolbarButton.onViewHiding = function({target}) {
  1066. target.parentNode.style.maxWidth = '';
  1067. target.firstChild.setAttribute('src', 'about:blank');
  1068. };
  1069. /******************************************************************************/
  1070. vAPI.toolbarButton.init();
  1071. /******************************************************************************/
  1072. vAPI.contextMenu = {
  1073. contextMap: {
  1074. frame: 'inFrame',
  1075. link: 'onLink',
  1076. image: 'onImage',
  1077. audio: 'onAudio',
  1078. video: 'onVideo',
  1079. editable: 'onEditableArea'
  1080. }
  1081. };
  1082. /******************************************************************************/
  1083. vAPI.contextMenu.displayMenuItem = function(e) {
  1084. var doc = e.target.ownerDocument;
  1085. var gContextMenu = doc.defaultView.gContextMenu;
  1086. if ( !gContextMenu.browser ) {
  1087. return;
  1088. }
  1089. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1090. var currentURI = gContextMenu.browser.currentURI;
  1091. // https://github.com/gorhill/uBlock/issues/105
  1092. // TODO: Should the element picker works on any kind of pages?
  1093. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1094. menuitem.hidden = true;
  1095. return;
  1096. }
  1097. var ctx = vAPI.contextMenu.contexts;
  1098. if ( !ctx ) {
  1099. menuitem.hidden = false;
  1100. return;
  1101. }
  1102. var ctxMap = vAPI.contextMenu.contextMap;
  1103. for ( var context of ctx ) {
  1104. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1105. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1106. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1107. menuitem.hidden = false;
  1108. return;
  1109. }
  1110. if ( gContextMenu[ctxMap[context]] ) {
  1111. menuitem.hidden = false;
  1112. return;
  1113. }
  1114. }
  1115. menuitem.hidden = true;
  1116. };
  1117. /******************************************************************************/
  1118. vAPI.contextMenu.register = function(doc) {
  1119. if ( !this.menuItemId ) {
  1120. return;
  1121. }
  1122. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1123. var menuitem = doc.createElement('menuitem');
  1124. menuitem.setAttribute('id', this.menuItemId);
  1125. menuitem.setAttribute('label', this.menuLabel);
  1126. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1127. menuitem.setAttribute('class', 'menuitem-iconic');
  1128. menuitem.addEventListener('command', this.onCommand);
  1129. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1130. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1131. };
  1132. /******************************************************************************/
  1133. vAPI.contextMenu.unregister = function(doc) {
  1134. if ( !this.menuItemId ) {
  1135. return;
  1136. }
  1137. var menuitem = doc.getElementById(this.menuItemId);
  1138. var contextMenu = menuitem.parentNode;
  1139. menuitem.removeEventListener('command', this.onCommand);
  1140. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1141. contextMenu.removeChild(menuitem);
  1142. };
  1143. /******************************************************************************/
  1144. vAPI.contextMenu.create = function(details, callback) {
  1145. this.menuItemId = details.id;
  1146. this.menuLabel = details.title;
  1147. this.contexts = details.contexts;
  1148. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1149. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1150. } else {
  1151. // default in Chrome
  1152. this.contexts = ['page'];
  1153. }
  1154. this.onCommand = function() {
  1155. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1156. var details = {
  1157. menuItemId: this.id
  1158. };
  1159. if ( gContextMenu.inFrame ) {
  1160. details.tagName = 'iframe';
  1161. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1162. } else if ( gContextMenu.onImage ) {
  1163. details.tagName = 'img';
  1164. details.srcUrl = gContextMenu.mediaURL;
  1165. } else if ( gContextMenu.onAudio ) {
  1166. details.tagName = 'audio';
  1167. details.srcUrl = gContextMenu.mediaURL;
  1168. } else if ( gContextMenu.onVideo ) {
  1169. details.tagName = 'video';
  1170. details.srcUrl = gContextMenu.mediaURL;
  1171. } else if ( gContextMenu.onLink ) {
  1172. details.tagName = 'a';
  1173. details.linkUrl = gContextMenu.linkURL;
  1174. }
  1175. callback(details, {
  1176. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1177. url: gContextMenu.browser.currentURI.asciiSpec
  1178. });
  1179. };
  1180. for ( var win of vAPI.tabs.getWindows() ) {
  1181. this.register(win.document);
  1182. }
  1183. };
  1184. /******************************************************************************/
  1185. vAPI.contextMenu.remove = function() {
  1186. for ( var win of vAPI.tabs.getWindows() ) {
  1187. this.unregister(win.document);
  1188. }
  1189. this.menuItemId = null;
  1190. this.menuLabel = null;
  1191. this.contexts = null;
  1192. this.onCommand = null;
  1193. };
  1194. /******************************************************************************/
  1195. vAPI.lastError = function() {
  1196. return null;
  1197. };
  1198. /******************************************************************************/
  1199. // This is called only once, when everything has been loaded in memory after
  1200. // the extension was launched. It can be used to inject content scripts
  1201. // in already opened web pages, to remove whatever nuisance could make it to
  1202. // the web pages before uBlock was ready.
  1203. vAPI.onLoadAllCompleted = function() {};
  1204. /******************************************************************************/
  1205. // Likelihood is that we do not have to punycode: given punycode overhead,
  1206. // it's faster to check and skip than do it unconditionally all the time.
  1207. var punycodeHostname = punycode.toASCII;
  1208. var isNotASCII = /[^\x21-\x7F]/;
  1209. vAPI.punycodeHostname = function(hostname) {
  1210. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1211. };
  1212. vAPI.punycodeURL = function(url) {
  1213. if ( isNotASCII.test(url) ) {
  1214. return Services.io.newURI(url, null, null).asciiSpec;
  1215. }
  1216. return url;
  1217. };
  1218. /******************************************************************************/
  1219. // clean up when the extension is disabled
  1220. window.addEventListener('unload', function() {
  1221. for ( var cleanup of cleanupTasks ) {
  1222. cleanup();
  1223. }
  1224. // frameModule needs to be cleared too
  1225. var frameModule = {};
  1226. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1227. frameModule.contentObserver.unregister();
  1228. Cu.unload(vAPI.getURL('frameModule.js'));
  1229. });
  1230. /******************************************************************************/
  1231. })();
  1232. /******************************************************************************/