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.

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