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.

1482 lines
42 KiB

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