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.

1525 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.6'
  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;
  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 : -1;
  290. }
  291. i = gBrowser.browsers.indexOf(target);
  292. if ( i !== -1 ) {
  293. i = gBrowser.tabs[i].linkedPanel;
  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="' + 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="' + 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: channelData[0] === this.MAIN_FRAME ? -1 : 0,
  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 !== lastRequest.openerURL ) {
  771. continue
  772. }
  773. sourceTabId = vAPI.tabs.getTabId(tab);
  774. if ( sourceTabId !== lastRequest.tabId ) {
  775. break;
  776. }
  777. sourceTabId = null;
  778. }
  779. if ( this.handlePopup(channel.URI, lastRequest.tabId, sourceTabId) ) {
  780. channel.cancel(this.ABORT);
  781. return;
  782. }
  783. }
  784. if ( this.handleRequest(channel, lastRequest) ) {
  785. return;
  786. }
  787. // If request is not handled we may use the data in on-modify-request
  788. if ( channel instanceof Ci.nsIWritablePropertyBag ) {
  789. channel.setProperty(
  790. location.host + 'reqdata',
  791. [lastRequest.type, lastRequest.tabId, sourceTabId]
  792. );
  793. }
  794. },
  795. // contentPolicy.shouldLoad doesn't detect redirects, this needs to be used
  796. asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback) {
  797. var result = this.ACCEPT;
  798. // If error thrown, the redirect will fail
  799. try {
  800. // skip internal redirects?
  801. /*if ( flags & 4 ) {
  802. console.log('internal redirect skipped');
  803. return;
  804. }*/
  805. var URI = newChannel.URI;
  806. if ( !URI.schemeIs('http') && !URI.schemeIs('https') ) {
  807. return;
  808. }
  809. if ( !(oldChannel instanceof Ci.nsIWritablePropertyBag) ) {
  810. return;
  811. }
  812. var channelData = oldChannel.getProperty(location.host + 'reqdata');
  813. var [type, tabId, sourceTabId] = channelData;
  814. if ( this.handlePopup(URI, tabId, sourceTabId) ) {
  815. result = this.ABORT;
  816. return;
  817. }
  818. var details = {
  819. type: type,
  820. tabId: tabId,
  821. // well...
  822. frameId: type === this.MAIN_FRAME ? -1 : 0,
  823. parentFrameId: -1
  824. };
  825. if ( this.handleRequest(newChannel, details) ) {
  826. result = this.ABORT;
  827. return;
  828. }
  829. // Carry the data on in case of multiple redirects
  830. if ( newChannel instanceof Ci.nsIWritablePropertyBag ) {
  831. newChannel.setProperty(location.host + 'reqdata', channelData);
  832. }
  833. } catch (ex) {
  834. // console.error(ex);
  835. } finally {
  836. callback.onRedirectVerifyCallback(result);
  837. }
  838. }
  839. };
  840. /******************************************************************************/
  841. vAPI.net = {};
  842. /******************************************************************************/
  843. vAPI.net.registerListeners = function() {
  844. // Since it's not used
  845. this.onBeforeSendHeaders = null;
  846. this.onBeforeRequest.types = new Set(this.onBeforeRequest.types);
  847. var shouldLoadListenerMessageName = location.host + ':shouldLoad';
  848. var shouldLoadListener = function(e) {
  849. var details = e.data;
  850. // data: and about:blank
  851. if ( details.url.charAt(0) !== 'h' ) {
  852. vAPI.net.onBeforeRequest.callback({
  853. url: 'http://' + details.url.slice(0, details.url.indexOf(':')),
  854. type: 'main_frame',
  855. tabId: vAPI.tabs.getTabId(e.target),
  856. frameId: details.frameId,
  857. parentFrameId: details.parentFrameId
  858. });
  859. return;
  860. }
  861. var lastRequest = httpObserver.lastRequest;
  862. lastRequest.url = details.url;
  863. lastRequest.type = details.type;
  864. lastRequest.tabId = vAPI.tabs.getTabId(e.target);
  865. lastRequest.frameId = details.frameId;
  866. lastRequest.parentFrameId = details.parentFrameId;
  867. lastRequest.openerURL = details.openerURL;
  868. };
  869. vAPI.messaging.globalMessageManager.addMessageListener(
  870. shouldLoadListenerMessageName,
  871. shouldLoadListener
  872. );
  873. httpObserver.register();
  874. cleanupTasks.push(function() {
  875. vAPI.messaging.globalMessageManager.removeMessageListener(
  876. shouldLoadListenerMessageName,
  877. shouldLoadListener
  878. );
  879. httpObserver.unregister();
  880. });
  881. };
  882. /******************************************************************************/
  883. vAPI.toolbarButton = {
  884. id: location.host + '-button',
  885. type: 'view',
  886. viewId: location.host + '-panel',
  887. label: vAPI.app.name,
  888. tooltiptext: vAPI.app.name,
  889. tabs: {/*tabId: {badge: 0, img: boolean}*/}
  890. };
  891. /******************************************************************************/
  892. vAPI.toolbarButton.init = function() {
  893. try {
  894. var {CustomizableUI} = Cu.import('resource:///modules/CustomizableUI.jsm', null);
  895. } catch (ex) {
  896. return;
  897. }
  898. this.defaultArea = CustomizableUI.AREA_NAVBAR;
  899. this.styleURI = [
  900. '#' + this.id + ' {',
  901. 'list-style-image: url(',
  902. vAPI.getURL('img/browsericons/icon16-off.svg'),
  903. ');',
  904. '}',
  905. '#' + this.viewId + ', #' + this.viewId + ' > iframe {',
  906. 'width: 160px;',
  907. 'height: 290px;',
  908. 'overflow: hidden !important;',
  909. '}'
  910. ];
  911. var platformVersion = Services.appinfo.platformVersion;
  912. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  913. this.styleURI.push(
  914. '#' + this.id + '[badge]:not([badge=""])::after {',
  915. 'position: absolute;',
  916. 'margin-left: -16px;',
  917. 'margin-top: 3px;',
  918. 'padding: 1px 2px;',
  919. 'font-size: 9px;',
  920. 'font-weight: bold;',
  921. 'color: #fff;',
  922. 'background: #666;',
  923. 'content: attr(badge);',
  924. '}'
  925. );
  926. }
  927. this.styleURI = Services.io.newURI(
  928. 'data:text/css,' + encodeURIComponent(this.styleURI.join('')),
  929. null,
  930. null
  931. );
  932. this.closePopup = function({target}) {
  933. CustomizableUI.hidePanelForNode(
  934. target.ownerDocument.getElementById(vAPI.toolbarButton.viewId)
  935. );
  936. };
  937. CustomizableUI.createWidget(this);
  938. vAPI.messaging.globalMessageManager.addMessageListener(
  939. location.host + ':closePopup',
  940. this.closePopup
  941. );
  942. cleanupTasks.push(function() {
  943. CustomizableUI.destroyWidget(this.id);
  944. vAPI.messaging.globalMessageManager.removeMessageListener(
  945. location.host + ':closePopup',
  946. this.closePopup
  947. );
  948. for ( var win of vAPI.tabs.getWindows() ) {
  949. var panel = win.document.getElementById(this.viewId);
  950. panel.parentNode.removeChild(panel);
  951. win.QueryInterface(Ci.nsIInterfaceRequestor)
  952. .getInterface(Ci.nsIDOMWindowUtils)
  953. .removeSheet(this.styleURI, 1);
  954. }
  955. }.bind(this));
  956. };
  957. /******************************************************************************/
  958. vAPI.toolbarButton.onBeforeCreated = function(doc) {
  959. var panel = doc.createElement('panelview');
  960. panel.setAttribute('id', this.viewId);
  961. var iframe = doc.createElement('iframe');
  962. iframe.setAttribute('type', 'content');
  963. doc.getElementById('PanelUI-multiView')
  964. .appendChild(panel)
  965. .appendChild(iframe);
  966. var updateTimer = null;
  967. var delayedResize = function() {
  968. if ( updateTimer ) {
  969. return;
  970. }
  971. updateTimer = setTimeout(resizePopup, 20);
  972. };
  973. var resizePopup = function() {
  974. var body = iframe.contentDocument.body;
  975. panel.parentNode.style.maxWidth = 'none';
  976. // Set the hegiht first, then the width for proper resising
  977. panel.style.height = iframe.style.height = body.clientHeight + 'px';
  978. panel.style.width = iframe.style.width = body.clientWidth + 'px';
  979. updateTimer = null;
  980. };
  981. var onPopupReady = function() {
  982. var win = this.contentWindow;
  983. if ( !win || win.location.host !== location.host ) {
  984. return;
  985. }
  986. new win.MutationObserver(delayedResize).observe(win.document.body, {
  987. attributes: true,
  988. characterData: true,
  989. subtree: true
  990. });
  991. delayedResize();
  992. };
  993. iframe.addEventListener('load', onPopupReady, true);
  994. doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor)
  995. .getInterface(Ci.nsIDOMWindowUtils)
  996. .loadSheet(this.styleURI, 1);
  997. };
  998. /******************************************************************************/
  999. vAPI.toolbarButton.onCreated = function(button) {
  1000. var platformVersion = Services.appinfo.platformVersion;
  1001. if ( Services.vc.compare(platformVersion, '36.0') < 0 ) {
  1002. return;
  1003. }
  1004. button.setAttribute('badge', '');
  1005. button.classList.add('badged-button');
  1006. setTimeout(function() {
  1007. var badge = button.ownerDocument.getAnonymousElementByAttribute(
  1008. button,
  1009. 'class',
  1010. 'toolbarbutton-badge'
  1011. );
  1012. if ( !badge ) {
  1013. return;
  1014. }
  1015. badge.style.cssText = [
  1016. 'position: absolute;',
  1017. 'bottom: 0;',
  1018. 'right: 0;',
  1019. 'padding: 1px;',
  1020. 'background: #666;',
  1021. 'color: #fff;',
  1022. 'font-size: 9px;',
  1023. 'font-weight: bold;'
  1024. ].join('');
  1025. }, 1000);
  1026. };
  1027. /******************************************************************************/
  1028. vAPI.toolbarButton.onViewShowing = function({target}) {
  1029. target.firstChild.setAttribute('src', vAPI.getURL('popup.html'));
  1030. };
  1031. /******************************************************************************/
  1032. vAPI.toolbarButton.onViewHiding = function({target}) {
  1033. target.parentNode.style.maxWidth = '';
  1034. target.firstChild.setAttribute('src', 'about:blank');
  1035. };
  1036. /******************************************************************************/
  1037. vAPI.toolbarButton.init();
  1038. /******************************************************************************/
  1039. vAPI.contextMenu = {
  1040. contextMap: {
  1041. frame: 'inFrame',
  1042. link: 'onLink',
  1043. image: 'onImage',
  1044. audio: 'onAudio',
  1045. video: 'onVideo',
  1046. editable: 'onEditableArea'
  1047. }
  1048. };
  1049. /******************************************************************************/
  1050. vAPI.contextMenu.displayMenuItem = function(e) {
  1051. var doc = e.target.ownerDocument;
  1052. var gContextMenu = doc.defaultView.gContextMenu;
  1053. if ( !gContextMenu.browser ) {
  1054. return;
  1055. }
  1056. var menuitem = doc.getElementById(vAPI.contextMenu.menuItemId);
  1057. var currentURI = gContextMenu.browser.currentURI;
  1058. if ( !currentURI.schemeIs('http') && !currentURI.schemeIs('https') ) {
  1059. menuitem.hidden = true;
  1060. return;
  1061. }
  1062. var ctx = vAPI.contextMenu.contexts;
  1063. if ( !ctx ) {
  1064. menuitem.hidden = false;
  1065. return;
  1066. }
  1067. var ctxMap = vAPI.contextMenu.contextMap;
  1068. for ( var context of ctx ) {
  1069. if ( context === 'page' && !gContextMenu.onLink && !gContextMenu.onImage
  1070. && !gContextMenu.onEditableArea && !gContextMenu.inFrame
  1071. && !gContextMenu.onVideo && !gContextMenu.onAudio ) {
  1072. menuitem.hidden = false;
  1073. return;
  1074. }
  1075. if ( gContextMenu[ctxMap[context]] ) {
  1076. menuitem.hidden = false;
  1077. return;
  1078. }
  1079. }
  1080. menuitem.hidden = true;
  1081. };
  1082. /******************************************************************************/
  1083. vAPI.contextMenu.register = function(doc) {
  1084. if ( !this.menuItemId ) {
  1085. return;
  1086. }
  1087. var contextMenu = doc.getElementById('contentAreaContextMenu');
  1088. var menuitem = doc.createElement('menuitem');
  1089. menuitem.setAttribute('id', this.menuItemId);
  1090. menuitem.setAttribute('label', this.menuLabel);
  1091. menuitem.setAttribute('image', vAPI.getURL('img/browsericons/icon16.svg'));
  1092. menuitem.setAttribute('class', 'menuitem-iconic');
  1093. menuitem.addEventListener('command', this.onCommand);
  1094. contextMenu.addEventListener('popupshowing', this.displayMenuItem);
  1095. contextMenu.insertBefore(menuitem, doc.getElementById('inspect-separator'));
  1096. };
  1097. /******************************************************************************/
  1098. vAPI.contextMenu.unregister = function(doc) {
  1099. if ( !this.menuItemId ) {
  1100. return;
  1101. }
  1102. var menuitem = doc.getElementById(this.menuItemId);
  1103. var contextMenu = menuitem.parentNode;
  1104. menuitem.removeEventListener('command', this.onCommand);
  1105. contextMenu.removeEventListener('popupshowing', this.displayMenuItem);
  1106. contextMenu.removeChild(menuitem);
  1107. };
  1108. /******************************************************************************/
  1109. vAPI.contextMenu.create = function(details, callback) {
  1110. this.menuItemId = details.id;
  1111. this.menuLabel = details.title;
  1112. this.contexts = details.contexts;
  1113. if ( Array.isArray(this.contexts) && this.contexts.length ) {
  1114. this.contexts = this.contexts.indexOf('all') === -1 ? this.contexts : null;
  1115. } else {
  1116. // default in Chrome
  1117. this.contexts = ['page'];
  1118. }
  1119. this.onCommand = function() {
  1120. var gContextMenu = this.ownerDocument.defaultView.gContextMenu;
  1121. var details = {
  1122. menuItemId: this.id
  1123. };
  1124. if ( gContextMenu.inFrame ) {
  1125. details.tagName = 'iframe';
  1126. details.frameUrl = gContextMenu.focusedWindow.location.href;
  1127. } else if ( gContextMenu.onImage ) {
  1128. details.tagName = 'img';
  1129. details.srcUrl = gContextMenu.mediaURL;
  1130. } else if ( gContextMenu.onAudio ) {
  1131. details.tagName = 'audio';
  1132. details.srcUrl = gContextMenu.mediaURL;
  1133. } else if ( gContextMenu.onVideo ) {
  1134. details.tagName = 'video';
  1135. details.srcUrl = gContextMenu.mediaURL;
  1136. } else if ( gContextMenu.onLink ) {
  1137. details.tagName = 'a';
  1138. details.linkUrl = gContextMenu.linkURL;
  1139. }
  1140. callback(details, {
  1141. id: vAPI.tabs.getTabId(gContextMenu.browser),
  1142. url: gContextMenu.browser.currentURI.asciiSpec
  1143. });
  1144. };
  1145. for ( var win of vAPI.tabs.getWindows() ) {
  1146. this.register(win.document);
  1147. }
  1148. };
  1149. /******************************************************************************/
  1150. vAPI.contextMenu.remove = function() {
  1151. for ( var win of vAPI.tabs.getWindows() ) {
  1152. this.unregister(win.document);
  1153. }
  1154. this.menuItemId = null;
  1155. this.menuLabel = null;
  1156. this.contexts = null;
  1157. this.onCommand = null;
  1158. };
  1159. /******************************************************************************/
  1160. vAPI.lastError = function() {
  1161. return null;
  1162. };
  1163. /******************************************************************************/
  1164. // This is called only once, when everything has been loaded in memory after
  1165. // the extension was launched. It can be used to inject content scripts
  1166. // in already opened web pages, to remove whatever nuisance could make it to
  1167. // the web pages before uBlock was ready.
  1168. vAPI.onLoadAllCompleted = function() {};
  1169. /******************************************************************************/
  1170. // Likelihood is that we do not have to punycode: given punycode overhead,
  1171. // it's faster to check and skip than do it unconditionally all the time.
  1172. var punycodeHostname = punycode.toASCII;
  1173. var isNotASCII = /[^\x21-\x7F]/;
  1174. vAPI.punycodeHostname = function(hostname) {
  1175. return isNotASCII.test(hostname) ? punycodeHostname(hostname) : hostname;
  1176. };
  1177. vAPI.punycodeURL = function(url) {
  1178. if ( isNotASCII.test(url) ) {
  1179. return Services.io.newURI(url, null, null).asciiSpec;
  1180. }
  1181. return url;
  1182. };
  1183. /******************************************************************************/
  1184. // clean up when the extension is disabled
  1185. window.addEventListener('unload', function() {
  1186. for ( var cleanup of cleanupTasks ) {
  1187. cleanup();
  1188. }
  1189. // frameModule needs to be cleared too
  1190. var frameModule = {};
  1191. Cu.import(vAPI.getURL('frameModule.js'), frameModule);
  1192. frameModule.contentObserver.unregister();
  1193. Cu.unload(vAPI.getURL('frameModule.js'));
  1194. });
  1195. /******************************************************************************/
  1196. })();
  1197. /******************************************************************************/