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.

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