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.

1475 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
  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.0'
  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. 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. typeMap: {
  603. 2: 'script',
  604. 3: 'image',
  605. 4: 'stylesheet',
  606. 5: 'object',
  607. 6: 'main_frame',
  608. 7: 'sub_frame',
  609. 11: 'xmlhttprequest'
  610. },
  611. lastRequest: {
  612. url: null,
  613. type: null,
  614. tabId: null,
  615. frameId: null,
  616. parentFrameId: null,
  617. openerURL: null
  618. },
  619. get componentRegistrar() {
  620. return Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
  621. },
  622. get categoryManager() {
  623. return Cc['@mozilla.org/categorymanager;1']
  624. .getService(Ci.nsICategoryManager);
  625. },
  626. QueryInterface: (function() {
  627. var {XPCOMUtils} = Cu.import('resource://gre/modules/XPCOMUtils.jsm', null);
  628. return XPCOMUtils.generateQI([
  629. Ci.nsIFactory,
  630. Ci.nsIObserver,
  631. Ci.nsIChannelEventSink,
  632. Ci.nsISupportsWeakReference
  633. ]);
  634. })(),
  635. createInstance: function(outer, iid) {
  636. if ( outer ) {
  637. throw Components.results.NS_ERROR_NO_AGGREGATION;
  638. }
  639. return this.QueryInterface(iid);
  640. },
  641. register: function() {
  642. Services.obs.addObserver(this, 'http-on-opening-request', true);
  643. Services.obs.addObserver(this, 'http-on-examine-response', true);
  644. this.componentRegistrar.registerFactory(
  645. this.classID,
  646. this.classDescription,
  647. this.contractID,
  648. this
  649. );
  650. this.categoryManager.addCategoryEntry(
  651. 'net-channel-event-sinks',
  652. this.contractID,
  653. this.contractID,
  654. false,
  655. true
  656. );
  657. },
  658. unregister: function() {
  659. Services.obs.removeObserver(this, 'http-on-opening-request');
  660. Services.obs.removeObserver(this, 'http-on-examine-response');
  661. this.componentRegistrar.unregisterFactory(this.classID, this);
  662. this.categoryManager.deleteCategoryEntry(
  663. 'net-channel-event-sinks',
  664. this.contractID,
  665. false
  666. );
  667. },
  668. handlePopup: function(URI, tabId, sourceTabId) {
  669. if ( !sourceTabId ) {
  670. return false;
  671. }
  672. if ( URI.scheme !== 'http' && URI.scheme !== 'https' ) {
  673. return false;
  674. }
  675. var result = vAPI.tabs.onPopup({
  676. tabId: tabId,
  677. sourceTabId: sourceTabId,
  678. url: URI.spec
  679. });
  680. return result === true;
  681. },
  682. handleRequest: function(channel, details) {
  683. var onBeforeRequest = vAPI.net.onBeforeRequest;
  684. var type = this.typeMap[details.type] || 'other';
  685. if ( onBeforeRequest.types.has(type) === false ) {
  686. return false;
  687. }
  688. var result = onBeforeRequest.callback({
  689. url: channel.URI.spec,
  690. type: type,
  691. tabId: details.tabId,
  692. frameId: details.frameId,
  693. parentFrameId: details.parentFrameId
  694. });
  695. if ( !result || typeof result !== 'object' ) {
  696. return false;
  697. }
  698. if ( result.cancel === true ) {
  699. channel.cancel(this.ABORT);
  700. return true;
  701. } else if ( result.redirectUrl ) {
  702. channel.redirectionLimit = 1;
  703. channel.redirectTo(
  704. Services.io.newURI(result.redirectUrl, null, null)
  705. );
  706. return true;
  707. }
  708. return false;
  709. },
  710. observe: function(channel, topic) {
  711. if ( !(channel instanceof Ci.nsIHttpChannel) ) {
  712. return;
  713. }
  714. var URI = channel.URI;
  715. var channelData, result;
  716. if ( topic === 'http-on-examine-response' ) {
  717. if ( !(channel instanceof Ci.nsIWritablePropertyBag) ) {
  718. return;
  719. }
  720. try {
  721. // [tabId, type, sourceTabId - given if it was a popup]
  722. channelData = channel.getProperty(location.host + 'reqdata');
  723. } catch (ex) {
  724. return;
  725. }
  726. if ( !channelData || channelData[0] !== this.MAIN_FRAME ) {
  727. return;
  728. }
  729. topic = 'Content-Security-Policy';
  730. try {
  731. result = channel.getResponseHeader(topic);
  732. } catch (ex) {
  733. result = null;
  734. }
  735. result = vAPI.net.onHeadersReceived.callback({
  736. url: URI.spec,
  737. tabId: channelData[1],
  738. parentFrameId: -1,
  739. responseHeaders: result ? [{name: topic, value: result}] : []
  740. });
  741. if ( result ) {
  742. channel.setResponseHeader(
  743. topic,
  744. result.responseHeaders.pop().value,
  745. true
  746. );
  747. }
  748. return;
  749. }
  750. // http-on-opening-request
  751. var lastRequest = this.lastRequest;
  752. if ( !lastRequest.url || lastRequest.url !== URI.spec ) {
  753. lastRequest.url = null;
  754. return;
  755. }
  756. // Important! When loading file via XHR for mirroring,
  757. // the URL will be the same, so it could fall into an infinite loop
  758. lastRequest.url = null;
  759. var sourceTabId = null;
  760. // Popup candidate (only for main_frame type)
  761. if ( lastRequest.openerURL ) {
  762. for ( var tab of vAPI.tabs.getAll() ) {
  763. var tabURI = tab.linkedBrowser.currentURI;
  764. // Not the best approach
  765. if ( tabURI.spec === this.lastRequest.openerURL ) {
  766. sourceTabId = vAPI.tabs.getTabId(tab);
  767. break;
  768. }
  769. }
  770. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  771. channel.cancel(this.ABORT);
  772. return;
  773. }
  774. }
  775. if ( this.handleRequest(channel, lastRequest) ) {
  776. return;
  777. }
  778. // If request is not handled we may use the data in on-modify-request
  779. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  780. channel.setProperty(
  781. location.host + 'reqdata',
  782. [lastRequest.type, lastRequest.tabId, sourceTabId]
  783. );
  784. }
  785. },
  786. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  787. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  788. var result = this.ACCEPT;
  789. // If error thrown, the redirect will fail
  790. try {
  791. // skip internal redirects?
  792. /*if ( flags & 4 ) {
  793. console.log('internal redirect skipped');
  794. return;
  795. }*/
  796. var scheme = newChannel.URI.scheme;
  797. if ( scheme !== 'http' && scheme !== 'https' ) {
  798. return;
  799. }
  800. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  801. return;
  802. }
  803. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  804. var [type, tabId, sourceTabId] = channelData;
  805. if ( this.handlePopup(newChannel.URI, tabId, sourceTabId) ) {
  806. result = this.ABORT;
  807. return;
  808. }
  809. var details = {
  810. type: type,
  811. tabId: tabId,
  812. // well...
  813. frameId: type === this.MAIN_FRAME ? -1 : 0,
  814. parentFrameId: -1
  815. };
  816. if ( this.handleRequest(newChannel, details) ) {
  817. result = this.ABORT;
  818. return;
  819. }
  820. // Carry the data on in case of multiple redirects
  821. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  822. newChannel.setProperty(location.host + 'reqdata', channelData);
  823. }
  824. } catch (ex) {
  825. // console.error(ex);
  826. } finally {
  827. callback.onRedirectVerifyCallback(result);
  828. }
  829. }
  830. };
  831. /******************************************************************************/
  832. vAPI.net = {};
  833. /******************************************************************************/
  834. vAPI.net.registerListeners = function() {
  835. // Since it's not used
  836. this.onBeforeSendHeaders = null;
  837. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  838. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  839. var shouldLoadListener = function(e) {
  840. var details = e.data;
  841. // data: and about:blank
  842. if ( details.url.charAt(0) !== 'h' ) {
  843. vAPI.net.onBeforeRequest.callback({
  844. url: 'http://' + details.url.slice(0, details.url.indexOf(':')),
  845. type: 'main_frame',
  846. tabId: vAPI.tabs.getTabId(e.target),
  847. frameId: details.frameId,
  848. parentFrameId: details.parentFrameId
  849. });
  850. return;
  851. }
  852. var lastRequest = httpObserver.lastRequest;
  853. lastRequest.url = details.url;
  854. lastRequest.type = details.type;
  855. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  856. lastRequest.frameId = details.frameId;
  857. lastRequest.parentFrameId = details.parentFrameId;
  858. lastRequest.openerURL = details.openerURL;
  859. };
  860. vAPI.messaging.globalMessageManager.addMessageListener(
  861. shouldLoadListenerMessageName,
  862. shouldLoadListener
  863. );
  864. httpObserver.register();
  865. cleanupTasks.push(function() {
  866. vAPI.messaging.globalMessageManager.removeMessageListener(
  867. shouldLoadListenerMessageName,
  868. shouldLoadListener
  869. );
  870. httpObserver.unregister();
  871. });
  872. };
  873. /******************************************************************************/
  874. vAPI.toolbarButton = {
  875. id: location.host + '-button',
  876. type: 'view',
  877. viewId: location.host + '-panel',
  878. label: vAPI.app.name,
  879. tooltiptext: vAPI.app.name,
  880. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  881. };
  882. /******************************************************************************/
  883. vAPI.toolbarButton.init = function() {
  884. var {CustomizableUI} = Cu.import('resource:///modules/CustomizableUI.jsm', null);
  885. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  886. this.styleURI = [
  887. '#' + this.id + ' {',
  888. 'list-style-image: url(',
  889. vAPI.getURL('img/browsericons/icon16-off.svg'),
  890. ');',
  891. '}',
  892. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  893. 'width: 160px;',
  894. 'height: 290px;',
  895. 'overflow: hidden !important;',
  896. '}'
  897. ];
  898. var platformVersion = Services.appinfo.platformVersion;
  899. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  900. this.styleURI.push(
  901. '#' + this.id + '[badge]:not([badge=""])::after {',
  902. 'position: absolute;',
  903. 'margin-left: -16px;',
  904. 'margin-top: 3px;',
  905. 'padding: 1px 2px;',
  906. 'font-size: 9px;',
  907. 'font-weight: bold;',
  908. 'color: #fff;',
  909. 'background: #666;',
  910. 'content: attr(badge);',
  911. '}'
  912. );
  913. }
  914. this.styleURI = Services.io.newURI(
  915. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  916. null,
  917. null
  918. );
  919. this.closePopup = function({target}) {
  920. CustomizableUI.hidePanelForNode(
  921. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  922. );
  923. };
  924. CustomizableUI.createWidget(this);
  925. vAPI.messaging.globalMessageManager.addMessageListener(
  926. location.host + ':closePopup',
  927. this.closePopup
  928. );
  929. cleanupTasks.push(function() {
  930. CustomizableUI.destroyWidget(this.id);
  931. vAPI.messaging.globalMessageManager.removeMessageListener(
  932. location.host + ':closePopup',
  933. this.closePopup
  934. );
  935. for ( var win of vAPI.tabs.getWindows() ) {
  936. var panel = win.document.getElementById(this.viewId);
  937. panel.parentNode.removeChild(panel);
  938. win.QueryInterface(Ci.nsIInterfaceRequestor)
  939. .getInterface(Ci.nsIDOMWindowUtils)
  940. .removeSheet(this.styleURI, 1);
  941. }
  942. }.bind(this));
  943. };
  944. /******************************************************************************/
  945. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  946. var panel = doc.createElement('panelview');
  947. panel.setAttribute('id', this.viewId);
  948. var iframe = doc.createElement('iframe');
  949. iframe.setAttribute('type', 'content');
  950. doc.getElementById('PanelUI-multiView')
  951. .appendChild(panel)
  952. .appendChild(iframe);
  953. var updateTimer = null;
  954. var delayedResize = function() {
  955. if ( updateTimer ) {
  956. return;
  957. }
  958. updateTimer = setTimeout(resizePopup, 50);
  959. };
  960. var resizePopup = function() {
  961. var body = iframe.contentDocument.body;
  962. panel.parentNode.style.maxWidth = 'none';
  963. panel.style.width = iframe.style.width = body.clientWidth + 'px';
  964. panel.style.height = iframe.style.height = body.clientHeight + 'px';
  965. updateTimer = null;
  966. };
  967. var onPopupReady = function() {
  968. var win = this.contentWindow;
  969. if ( !win || win.location.host !== location.host ) {
  970. return;
  971. }
  972. new win.MutationObserver(delayedResize).observe(win.body, {
  973. attributes: true,
  974. characterData: true,
  975. subtree: true
  976. });
  977. delayedResize();
  978. };
  979. iframe.addEventListener('load', onPopupReady, true);
  980. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  981. .getInterface(Ci.nsIDOMWindowUtils)
  982. .loadSheet(this.styleURI, 1);
  983. };
  984. /******************************************************************************/
  985. vAPI.toolbarButton.onCreated = function(button) {
  986. var platformVersion = Services.appinfo.platformVersion;
  987. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  988. return;
  989. }
  990. button.setAttribute('badge', '');
  991. button.classList.add('badged-button');
  992. setTimeout(function() {
  993. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  994. button,
  995. 'class',
  996. 'toolbarbutton-badge'
  997. );
  998. if ( !badge ) {
  999. return;
  1000. }
  1001. badge.style.cssText = [
  1002. 'position: absolute;',
  1003. 'bottom: 0;',
  1004. 'right: 0;',
  1005. 'padding: 1px;',
  1006. 'background: #666;',
  1007. 'color: #fff;',
  1008. 'font-size: 9px;',
  1009. 'font-weight: bold;'
  1010. ].join('');
  1011. }, 1000);
  1012. };
  1013. /******************************************************************************/
  1014. vAPI.toolbarButton.onViewShowing = function({target}) {
  1015. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1016. };
  1017. /******************************************************************************/
  1018. vAPI.toolbarButton.onViewHiding = function({target}) {
  1019. target.parentNode.style.maxWidth = '';
  1020. target.firstChild.setAttribute('src', 'about:blank');
  1021. };
  1022. /******************************************************************************/
  1023. vAPI.toolbarButton.init();
  1024. /******************************************************************************/
  1025. vAPI.contextMenu = {
  1026. contextMap: {
  1027. frame: 'inFrame',
  1028. link: 'onLink',
  1029. image: 'onImage',
  1030. audio: 'onAudio',
  1031. video: 'onVideo',
  1032. editable: 'onEditableArea'
  1033. }
  1034. };
  1035. /******************************************************************************/
  1036. vAPI.contextMenu.displayMenuItem = function(e) {
  1037. var doc = e.target.ownerDocument;
  1038. var gContextMenu = doc.defaultView.gContextMenu;
  1039. if ( !gContextMenu.browser ) {
  1040. return;
  1041. }
  1042. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1043. if ( /^https?$/.test(gContextMenu.browser.currentURI.scheme) === false) {
  1044. menuitem.hidden = true;
  1045. return;
  1046. }
  1047. var ctx = vAPI.contextMenu.contexts;
  1048. if ( !ctx ) {
  1049. menuitem.hidden = false;
  1050. return;
  1051. }
  1052. var ctxMap = vAPI.contextMenu.contextMap;
  1053. for ( var context of ctx ) {
  1054. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1055. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1056. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1057. menuitem.hidden = false;
  1058. return;
  1059. }
  1060. if ( gContextMenu[ctxMap[context]] ) {
  1061. menuitem.hidden = false;
  1062. return;
  1063. }
  1064. }
  1065. menuitem.hidden = true;
  1066. };
  1067. /******************************************************************************/
  1068. vAPI.contextMenu.register = function(doc) {
  1069. if ( !this.menuItemId ) {
  1070. return;
  1071. }
  1072. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1073. var menuitem = doc.createElement('menuitem');
  1074. menuitem.setAttribute('id', this.menuItemId);
  1075. menuitem.setAttribute('label', this.menuLabel);
  1076. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1077. menuitem.setAttribute('class', 'menuitem-iconic');
  1078. menuitem.addEventListener('command', this.onCommand);
  1079. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1080. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1081. };
  1082. /******************************************************************************/
  1083. vAPI.contextMenu.unregister = function(doc) {
  1084. if ( !this.menuItemId ) {
  1085. return;
  1086. }
  1087. var menuitem = doc.getElementById(this.menuItemId);
  1088. var contextMenu = menuitem.parentNode;
  1089. menuitem.removeEventListener('command', this.onCommand);
  1090. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1091. contextMenu.removeChild(menuitem);
  1092. };
  1093. /******************************************************************************/
  1094. vAPI.contextMenu.create = function(details, callback) {
  1095. this.menuItemId = details.id;
  1096. this.menuLabel = details.title;
  1097. this.contexts = details.contexts;
  1098. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1099. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1100. } else {
  1101. // default in Chrome
  1102. this.contexts = ['page'];
  1103. }
  1104. this.onCommand = function() {
  1105. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1106. var details = {
  1107. menuItemId: this.id,
  1108. tagName: gContextMenu.target.tagName.toLowerCase()
  1109. };
  1110. if ( gContextMenu.inFrame ) {
  1111. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1112. } else if ( gContextMenu.onImage || gContextMenu.onAudio || gContextMenu.onVideo ) {
  1113. details.srcUrl = gContextMenu.mediaURL;
  1114. } else if ( gContextMenu.onLink ) {
  1115. details.linkUrl = gContextMenu.linkURL;
  1116. }
  1117. callback(details, {
  1118. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1119. url: gContextMenu.browser.currentURI.spec
  1120. });
  1121. };
  1122. for ( var win of vAPI.tabs.getWindows() ) {
  1123. this.register(win.document);
  1124. }
  1125. };
  1126. /******************************************************************************/
  1127. vAPI.contextMenu.remove = function() {
  1128. for ( var win of vAPI.tabs.getWindows() ) {
  1129. this.unregister(win.document);
  1130. }
  1131. this.menuItemId = null;
  1132. this.menuLabel = null;
  1133. this.contexts = null;
  1134. this.onCommand = null;
  1135. };
  1136. /******************************************************************************/
  1137. vAPI.lastError = function() {
  1138. return null;
  1139. };
  1140. /******************************************************************************/
  1141. // This is called only once, when everything has been loaded in memory after
  1142. // the extension was launched. It can be used to inject content scripts
  1143. // in already opened web pages, to remove whatever nuisance could make it to
  1144. // the web pages before uBlock was ready.
  1145. vAPI.onLoadAllCompleted = function() {};
  1146. /******************************************************************************/
  1147. // clean up when the extension is disabled
  1148. window.addEventListener('unload', function() {
  1149. for ( var cleanup of cleanupTasks ) {
  1150. cleanup();
  1151. }
  1152. // frameModule needs to be cleared too
  1153. var frameModule = {};
  1154. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1155. frameModule.contentObserver.unregister();
  1156. Cu.unload(vAPI.getURL('frameModule.js'));
  1157. });
  1158. /******************************************************************************/
  1159. })();
  1160. /******************************************************************************/