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.

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