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.

1504 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
  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.5.3'
  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. values.push(key);
  150. values.push(JSON.stringify(details[key]));
  151. placeholders.push('?, ?');
  152. }
  153. if ( !values.length ) {
  154. return;
  155. }
  156. SQLite.run(
  157. 'INSERT OR REPLACE INTO settings (name, value) SELECT ' +
  158. placeholders.join(' UNION SELECT '),
  159. values,
  160. callback
  161. );
  162. },
  163. remove: function(keys, callback) {
  164. if ( typeof keys === 'string' ) {
  165. keys = [keys];
  166. }
  167. SQLite.run(
  168. 'DELETE FROM settings' + this.sqlWhere('name', keys.length),
  169. keys,
  170. callback
  171. );
  172. },
  173. clear: function(callback) {
  174. SQLite.run('DELETE FROM settings');
  175. SQLite.run('VACUUM', null, callback);
  176. },
  177. getBytesInUse: function(keys, callback) {
  178. if ( typeof callback !== 'function' ) {
  179. return;
  180. }
  181. SQLite.run(
  182. 'SELECT "size" AS size, SUM(LENGTH(value)) FROM settings' +
  183. this.sqlWhere('name', Array.isArray(keys) ? keys.length : 0),
  184. keys,
  185. function(result) {
  186. callback(result.size);
  187. }
  188. );
  189. }
  190. };
  191. /******************************************************************************/
  192. var windowWatcher = {
  193. onTabClose: function(e) {
  194. var tabId = vAPI.tabs.getTabId(e.target);
  195. vAPI.tabs.onClosed(tabId);
  196. delete vAPI.toolbarButton.tabs[tabId];
  197. },
  198. onTabSelect: function(e) {
  199. vAPI.setIcon(
  200. vAPI.tabs.getTabId(e.target),
  201. e.target.ownerDocument.defaultView
  202. );
  203. },
  204. onReady: function(e) {
  205. if ( e ) {
  206. this.removeEventListener(e.type, windowWatcher.onReady);
  207. }
  208. var wintype = this.document.documentElement.getAttribute('windowtype');
  209. if ( wintype !== 'navigator:browser' ) {
  210. return;
  211. }
  212. if ( !this.gBrowser || !this.gBrowser.tabContainer ) {
  213. return;
  214. }
  215. var tC = this.gBrowser.tabContainer;
  216. this.gBrowser.addTabsProgressListener(tabsProgressListener);
  217. tC.addEventListener('TabClose', windowWatcher.onTabClose);
  218. tC.addEventListener('TabSelect', windowWatcher.onTabSelect);
  219. vAPI.contextMenu.register(this.document);
  220. // when new window is opened TabSelect doesn't run on the selected tab?
  221. },
  222. observe: function(win, topic) {
  223. if ( topic === 'domwindowopened' ) {
  224. win.addEventListener('DOMContentLoaded', this.onReady);
  225. }
  226. }
  227. };
  228. /******************************************************************************/
  229. var tabsProgressListener = {
  230. onLocationChange: function(browser, webProgress, request, location, flags) {
  231. if ( !webProgress.isTopLevel ) {
  232. return;
  233. }
  234. var tabId = vAPI.tabs.getTabId(browser);
  235. if ( flags & 1 ) {
  236. vAPI.tabs.onUpdated(tabId, {url: location.asciiSpec}, {
  237. frameId: 0,
  238. tabId: tabId,
  239. url: browser.currentURI.asciiSpec
  240. });
  241. } else if ( location.schemeIs('http') || location.schemeIs('https') ) {
  242. vAPI.tabs.onNavigation({
  243. frameId: 0,
  244. tabId: tabId,
  245. url: location.asciiSpec
  246. });
  247. }
  248. }
  249. };
  250. /******************************************************************************/
  251. vAPI.tabs = {};
  252. /******************************************************************************/
  253. vAPI.tabs.registerListeners = function() {
  254. // onNavigation and onUpdated handled with tabsProgressListener
  255. // onClosed - handled in windowWatcher.onTabClose
  256. // onPopup ?
  257. for ( var win of this.getWindows() ) {
  258. windowWatcher.onReady.call(win);
  259. }
  260. Services.ww.registerNotification(windowWatcher);
  261. cleanupTasks.push(function() {
  262. Services.ww.unregisterNotification(windowWatcher);
  263. for ( var win of vAPI.tabs.getWindows() ) {
  264. vAPI.contextMenu.unregister(win.document);
  265. win.removeEventListener('DOMContentLoaded', windowWatcher.onReady);
  266. win.gBrowser.removeTabsProgressListener(tabsProgressListener);
  267. var tC = win.gBrowser.tabContainer;
  268. tC.removeEventListener('TabClose', windowWatcher.onTabClose);
  269. tC.removeEventListener('TabSelect', windowWatcher.onTabSelect);
  270. // close extension tabs
  271. for ( var tab of win.gBrowser.tabs ) {
  272. var URI = tab.linkedBrowser.currentURI;
  273. if ( URI.schemeIs('chrome') && URI.host === location.host ) {
  274. win.gBrowser.removeTab(tab);
  275. }
  276. }
  277. }
  278. });
  279. };
  280. /******************************************************************************/
  281. vAPI.tabs.getTabId = function(target) {
  282. if ( target.linkedPanel ) {
  283. return target.linkedPanel.slice(6);
  284. }
  285. var i, gBrowser = target.ownerDocument.defaultView.gBrowser;
  286. // This should be more efficient from version 35
  287. if ( gBrowser.getTabForBrowser ) {
  288. i = gBrowser.getTabForBrowser(target);
  289. return i ? i.linkedPanel.slice(6) : -1;
  290. }
  291. i = gBrowser.browsers.indexOf(target);
  292. if ( i !== -1 ) {
  293. i = gBrowser.tabs[i].linkedPanel.slice(6);
  294. }
  295. return i;
  296. };
  297. /******************************************************************************/
  298. vAPI.tabs.get = function(tabId, callback) {
  299. var tab, windows;
  300. if ( tabId === null ) {
  301. tab = Services.wm.getMostRecentWindow('navigator:browser').gBrowser.selectedTab;
  302. tabId = vAPI.tabs.getTabId(tab);
  303. } else {
  304. windows = this.getWindows();
  305. for ( var win of windows ) {
  306. tab = win.gBrowser.tabContainer.querySelector(
  307. 'tab[linkedpanel="panel-' + tabId + '"]'
  308. );
  309. if ( tab ) {
  310. break;
  311. }
  312. }
  313. }
  314. // for internal use
  315. if ( typeof callback !== 'function' ) {
  316. return tab;
  317. }
  318. if ( !tab ) {
  319. callback();
  320. return;
  321. }
  322. var browser = tab.linkedBrowser;
  323. var gBrowser = browser.ownerDocument.defaultView.gBrowser;
  324. if ( !windows ) {
  325. windows = this.getWindows();
  326. }
  327. callback({
  328. id: tabId,
  329. index: gBrowser.browsers.indexOf(browser),
  330. windowId: windows.indexOf(browser.ownerDocument.defaultView),
  331. active: tab === gBrowser.selectedTab,
  332. url: browser.currentURI.asciiSpec,
  333. title: tab.label
  334. });
  335. };
  336. /******************************************************************************/
  337. vAPI.tabs.getAll = function(window) {
  338. var win, tab, tabs = [];
  339. for ( win of this.getWindows() ) {
  340. if ( window && window !== win ) {
  341. continue;
  342. }
  343. for ( tab of win.gBrowser.tabs ) {
  344. tabs.push(tab);
  345. }
  346. }
  347. return tabs;
  348. };
  349. /******************************************************************************/
  350. vAPI.tabs.getWindows = function() {
  351. var winumerator = Services.wm.getEnumerator('navigator:browser');
  352. var windows = [];
  353. while ( winumerator.hasMoreElements() ) {
  354. var win = winumerator.getNext();
  355. if ( !win.closed ) {
  356. windows.push(win);
  357. }
  358. }
  359. return windows;
  360. };
  361. /******************************************************************************/
  362. // properties of the details object:
  363. // url: 'URL', // the address that will be opened
  364. // tabId: 1, // the tab is used if set, instead of creating a new one
  365. // index: -1, // undefined: end of the list, -1: following tab, or after index
  366. // active: false, // opens the tab in background - true and undefined: foreground
  367. // select: true // if a tab is already opened with that url, then select it instead of opening a new one
  368. vAPI.tabs.open = function(details) {
  369. if ( !details.url ) {
  370. return null;
  371. }
  372. // extension pages
  373. if ( /^[\w-]{2,}:/.test(details.url) === false ) {
  374. details.url = vAPI.getURL(details.url);
  375. }
  376. var tab, tabs;
  377. if ( details.select ) {
  378. var URI = Services.io.newURI(details.url, null, null);
  379. tabs = this.getAll();
  380. for ( tab of tabs ) {
  381. var browser = tab.linkedBrowser;
  382. // Or simply .equals if we care about the fragment
  383. if ( URI.equalsExceptRef(browser.currentURI) ) {
  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.schemeIs('http') && !URI.schemeIs('https') ) {
  675. return false;
  676. }
  677. var result = vAPI.tabs.onPopup({
  678. tabId: tabId,
  679. sourceTabId: sourceTabId,
  680. url: URI.asciiSpec
  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.asciiSpec,
  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.asciiSpec,
  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. // Probably isn't the best method to identify the source tab
  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 URI = newChannel.URI;
  802. if ( !URI.schemeIs('http') && !URI.schemeIs('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(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, 20);
  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. var currentURI = gContextMenu.browser.currentURI;
  1050. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1051. menuitem.hidden = true;
  1052. return;
  1053. }
  1054. var ctx = vAPI.contextMenu.contexts;
  1055. if ( !ctx ) {
  1056. menuitem.hidden = false;
  1057. return;
  1058. }
  1059. var ctxMap = vAPI.contextMenu.contextMap;
  1060. for ( var context of ctx ) {
  1061. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1062. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1063. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1064. menuitem.hidden = false;
  1065. return;
  1066. }
  1067. if ( gContextMenu[ctxMap[context]] ) {
  1068. menuitem.hidden = false;
  1069. return;
  1070. }
  1071. }
  1072. menuitem.hidden = true;
  1073. };
  1074. /******************************************************************************/
  1075. vAPI.contextMenu.register = function(doc) {
  1076. if ( !this.menuItemId ) {
  1077. return;
  1078. }
  1079. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1080. var menuitem = doc.createElement('menuitem');
  1081. menuitem.setAttribute('id', this.menuItemId);
  1082. menuitem.setAttribute('label', this.menuLabel);
  1083. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1084. menuitem.setAttribute('class', 'menuitem-iconic');
  1085. menuitem.addEventListener('command', this.onCommand);
  1086. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1087. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1088. };
  1089. /******************************************************************************/
  1090. vAPI.contextMenu.unregister = function(doc) {
  1091. if ( !this.menuItemId ) {
  1092. return;
  1093. }
  1094. var menuitem = doc.getElementById(this.menuItemId);
  1095. var contextMenu = menuitem.parentNode;
  1096. menuitem.removeEventListener('command', this.onCommand);
  1097. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1098. contextMenu.removeChild(menuitem);
  1099. };
  1100. /******************************************************************************/
  1101. vAPI.contextMenu.create = function(details, callback) {
  1102. this.menuItemId = details.id;
  1103. this.menuLabel = details.title;
  1104. this.contexts = details.contexts;
  1105. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1106. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1107. } else {
  1108. // default in Chrome
  1109. this.contexts = ['page'];
  1110. }
  1111. this.onCommand = function() {
  1112. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1113. var details = {
  1114. menuItemId: this.id,
  1115. tagName: gContextMenu.target.tagName.toLowerCase()
  1116. };
  1117. if ( gContextMenu.inFrame ) {
  1118. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1119. } else if ( gContextMenu.onImage || gContextMenu.onAudio || gContextMenu.onVideo ) {
  1120. details.srcUrl = gContextMenu.mediaURL;
  1121. } else if ( gContextMenu.onLink ) {
  1122. details.linkUrl = gContextMenu.linkURL;
  1123. }
  1124. callback(details, {
  1125. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1126. url: gContextMenu.browser.currentURI.asciiSpec
  1127. });
  1128. };
  1129. for ( var win of vAPI.tabs.getWindows() ) {
  1130. this.register(win.document);
  1131. }
  1132. };
  1133. /******************************************************************************/
  1134. vAPI.contextMenu.remove = function() {
  1135. for ( var win of vAPI.tabs.getWindows() ) {
  1136. this.unregister(win.document);
  1137. }
  1138. this.menuItemId = null;
  1139. this.menuLabel = null;
  1140. this.contexts = null;
  1141. this.onCommand = null;
  1142. };
  1143. /******************************************************************************/
  1144. vAPI.lastError = function() {
  1145. return null;
  1146. };
  1147. /******************************************************************************/
  1148. // This is called only once, when everything has been loaded in memory after
  1149. // the extension was launched. It can be used to inject content scripts
  1150. // in already opened web pages, to remove whatever nuisance could make it to
  1151. // the web pages before uBlock was ready.
  1152. vAPI.onLoadAllCompleted = function() {};
  1153. /******************************************************************************/
  1154. // Likelihood is that we do not have to punycode: given punycode overhead,
  1155. // it's faster to check and skip than do it unconditionally all the time.
  1156. var punycodeHostname = punycode.toASCII;
  1157. var isNotASCII = /[^\x21-\x7F]/;
  1158. vAPI.punycodeHostname = function(hostname) {
  1159. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1160. };
  1161. vAPI.punycodeURL = function(url) {
  1162. if ( isNotASCII.test(url) ) {
  1163. return Services.io.newURI(url, null, null).asciiSpec;
  1164. }
  1165. return url;
  1166. };
  1167. /******************************************************************************/
  1168. // clean up when the extension is disabled
  1169. window.addEventListener('unload', function() {
  1170. for ( var cleanup of cleanupTasks ) {
  1171. cleanup();
  1172. }
  1173. // frameModule needs to be cleared too
  1174. var frameModule = {};
  1175. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1176. frameModule.contentObserver.unregister();
  1177. Cu.unload(vAPI.getURL('frameModule.js'));
  1178. });
  1179. /******************************************************************************/
  1180. })();
  1181. /******************************************************************************/