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.

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