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.

1528 lines
43 KiB

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